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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM