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

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

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

 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来获取了截图,而且只能是在播放本地视频时才能使用。

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

 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 }
原文地址:https://www.cnblogs.com/zhengxt/p/4198109.html