变量如下:
private SurfaceHolder mSurfaceHolder; private MediaPlayer mPlayer;
构造函数内获取 SurfaceHolder,并设置回调接口 Callback:
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 播放视频:
/** * 播放视频 * @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(); }
至此,主要代码已贴出,其实相比视频录制(请看另一篇 仿微信小视频录制控件),视频播放相对简单,相信童鞋们一下就可以看明白。
完整代码请看:仿微信小视频播放控件