效果圖以下:canvas
變量以下:微信
private SurfaceHolder mSurfaceHolder; private MediaPlayer mPlayer;
構造函數內獲取 SurfaceHolder,並設置回調接口 Callback:ide
public MoviePlayerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mSurfaceHolder = this.getHolder(); mSurfaceHolder.addCallback(mSurfaceHolderCallback); // holder加入回調接口 mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// setType必須設置,要不出錯. } private Callback mSurfaceHolderCallback = new Callback() { @Override public void surfaceDestroyed(SurfaceHolder arg0) { mSurfaceHolder = null; } @Override public void surfaceCreated(SurfaceHolder arg0) { // TODO Auto-generated method stub mSurfaceHolder = arg0; } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub mSurfaceHolder = arg0; } };
自定義視頻播放成功回調接口:函數
/** * 播放成功回調 * @date 2015-2-9 */ public interface OnPlayCompletionListener{ public void onPlayCompletion(); }
經過設置 MediaPlayer 播放視頻:this
/** * 播放視頻 * @param fileName 文件路徑 */ public void play(String fileName, final OnPlayCompletionListener completionListener) { mPlayer = new MediaPlayer(); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mPlayer.setDisplay(mSurfaceHolder); // 定義一個SurfaceView播放它 mPlayer.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer arg0) { stop(); if(completionListener != null) completionListener.onPlayCompletion(); // canvas.drawColor(Color.TRANSPARENT, // PorterDuff.Mode.CLEAR); } }); try { mPlayer.setDataSource(fileName); mPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mPlayer.start(); }
至此,主要代碼已貼出,其實相比視頻錄製(請看另外一篇 仿微信小視頻錄製控件),視頻播放相對簡單,相信童鞋們一下就能夠看明白。.net
完整代碼請看:仿微信小視頻播放控件code
最近在運營一個有關反脆弱成長的我的公衆號,歡迎關注視頻