本例将介绍几种视频的播放方式,
一:调用系统默认播放器播放视频;
二:SurfaceView + MediaPlayer;
三:VideoView + MediaController;
四:HTML5 + WebView;
五:第三方包,Vitamio。
1,调用系统默认的播放器,采用Intent意图的方式调取系统默认的视频播放器:
//调用系统自带的播放器
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/*");
startActivity(intent);
2,使用SurfaceView + MediaPlayer 绘制视频播放:
首先,初始化SurfaceView,并设置Callback,Callback是SurfaceHolder的回掉函数,可以帮助控制SurfaceHolder
SurfaceView sv = (SurfaceView) findViewById(R.id.surface_view);
SurfaceHolder holder = sv.getHolder();
holder.addCallback(new MyCallback());
为了可以播放视频或者使用Camera预览,我们需要指定其Buffer类型 ,设置风格
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) sv.getLayoutParams();
lp.height = 640;
lp.width =640;
Log.d("tag","ViewGroup is created succese");
sv.setLayoutParams(lp);
其次,自定义callback,使其实现SurfaceHolder.Callback,用以监听SurfaceHolder的周期;
class MyCallback implements SurfaceHolder.Callback {
MediaPlayer player = new MediaPlayer();
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
player.setDisplay(holder);
player.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Download/video_480x360.mp4");
player.prepare();
Log.d("tag","Player is prepare");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(player.isPlaying()){
player.stop();
}
player.release();
Log.d("tag","Player is release");
}
}
3,使用VideoView + MediaController 播放
VideoView vv = (VideoView) findViewById(R.id.videoView);
MediaController mc=new MediaController(this);
vv.setMediaController(mc);
vv.setVideoURI(Uri.parse("http://172.17.29.120/localuser/ljy/video/hetang.3gp"));
vv.start();
vv.requestFocus();
4,使用HTML5 + WebView 播放
首先使用H5创建一个.html文件,使用video标签,把该.html放入到assets目录下
autoplay:自动播放
controls:控制器
src:视频地址
其次,在Android布局中创建一个布局,添加WebView控件:
wv.loadUrl("file:///android_asset/index.html");