废话不多说,直接上代码
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private VideoView videoView;
private Button btn_play,btn_stop,btn_pause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_play = (Button)findViewById(R.id.btn_play);
btn_stop = (Button)findViewById(R.id.stop);
videoView = (VideoView)findViewById(R.id.video_view);
btn_play.setOnClickListener(this);
btn_stop.setOnClickListener(this);
btn_pause.setOnClickListener(this);
initVideoPath();
}
private void initVideoPath() {
File file = new File(Environment.getExternalStorageDirectory(),"movie.mp4");//制定视频文件的路径
videoView.setVideoPath(file.getPath());//设置路径
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_play:
if(!videoView.isPlaying()) {
videoView.start();
}
break;
case R.id.btn_pause:
if(videoView.isPlaying()){
videoView.pause();
}
break;
case R.id.stop:
if(videoView.isPlaying()){
videoView.resume();
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(videoView != null){
videoView.suspend();
}
}
}
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical">
<VideoView
android:id="@+id/video_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="play"/>
<Button
android:id="@+id/btn_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pause"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop"/>
</LinearLayout>
</LinearLayout>
首先通过File对象获取到视频文件的路径,接着给VideoView设置路径。
就可以调用start()开始 pause()暂停 resume()重新播放方法。
在关闭时需要调用suspend()方法,将VideoView所占用的资源释放。