MediaPlayer配合SurfaceView或TextureView作视频播放器时的截图方法。

很久没写博客了,偷懒了半年。自从我下定决心辞职转行当程序员,开始投简历后就没写博客了。一直给本身找借口说太忙了没时间写。最近下定决心要从新开始写博客,虽然写的挫可是就看成一种学习记录吧。程序员

今天有空就说写下最近遇到的难题,须要在应用内截取一个视频播放器的当前画面拿来分享。播放器是用Android自己的MediaPlayer+TextureView实现的,使用View中的buildDrawingCache和getDrawingCache方法截图的时候,发现生成的Bitmap里只有UI布局,视频播放画面是不存在的。查了下API发现要得到当前TextureView显示的内容只须要调用getBitmap方法就能够。canvas

 1 private Bitmap getScreenshot(){
 2     mPlayerLayout.buildDrawingCache();
 3     Bitmap content = mTextureView.getBitmap();
 4     Bitmap layout  = mPlayerLayout.getDrawingCache();
 5     Bitmap screenshot = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(), Bitmap.Config.ARGB_4444);
 6     // 把两部分拼起来,先把视频截图绘制到上下左右居中的位置,再把播放器的布局元素绘制上去。
 7     Canvas canvas = new Canvas(screenshot);
 8     canvas.drawBitmap(content, (layout.getWidth()-content.getWidth())/2, (layout.getHeight()-content.getHeight())/2, new Paint());
 9     canvas.drawBitmap(layout, 0, 0, new Paint());
10     canvas.save();
11     canvas.restore();
12     return screenshot;
13 }

拿到TextureView里显示的视频内容和播放器的布局元素合成一个新的Bitmap就能够了。网络

可是由于TextureView是4.0后才有的,4.0如下只能使用SurfaceView。这样要截图就比较麻烦了。只能经过MediaMetadataRetriever来获取了截图,并且只能是在播放本地视频时才能使用。ide

播放网络视频时的截图方法暂时没找到,麻烦知道的朋友在评论区说下。布局

 1 private Bitmap getScreenshot(){
 2     mPlayerLayout.buildDrawingCache();
 3     Bitmap content = surfaceViewCapture();
 4     Bitmap layout  = mPlayerLayout.getDrawingCache();
 5     Bitmap screenshot = Bitmap.createBitmap(layout.getWidth(), layout.getHeight(), Bitmap.Config.ARGB_4444);
 6     // 把两部分拼起来,先把视频截图绘制到上下左右居中的位置,再把播放器的布局元素绘制上去。
 7     Canvas canvas = new Canvas(screenshot);
 8     canvas.drawBitmap(screen, (layout.getWidth()-screen.getWidth())/2, (layout.getHeight()-screen.getHeight())/2, new Paint());
 9     canvas.drawBitmap(layout, 0, 0, new Paint());
10     canvas.save();
11     canvas.restore();
12     return screenshot;
13 }
14     
15 private Bitmap surfaceViewCapture(){
16     MediaMetadataRetriever mmr = new MediaMetadataRetriever();
17     mmr.setDataSource(Environment.getExternalStorageDirectory()+"/video.mp4");
18     return mmr.getFrameAtTime(mMediaPlayer.getCurrentPosition() * 1000);
19 }
相关文章
相关标签/搜索