在Android中,我们有三种方式来实现视频的播放:
1、使用其自带的播放器。指定Action为ACTION_VIEW,Data为Uri,Type为其MIME类型。
2、使用VideoView来播放。在布局文件中使用VideoView结合MediaController来实现对其控制。
3、使用MediaPlayer类和SurfaceView来实现,这种方式很灵活。
今天在这里我们使用第二种和第三种
首先新建Activity和布局文件,布局文件入下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_video_play"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.myapplication.VideoPlayActivity">
<SurfaceView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="@+id/sv_avp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SeekBar
android:id="@+id/sb_amp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="isPlayorPause"
android:src="@android:drawable/ic_media_play" />
</LinearLayout>
</LinearLayout>
与上一篇的布局并无二致,只是多了SurfaceView用以捕捉MediaPlayer的画面,设置SurfaceView捕捉MediaPlayer的画面的代码入下
surfaceView = (SurfaceView) findViewById(R.id.sv_avp);
SurfaceHolder surfaceHolder= surfaceView.getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(surfaceView.getHolder());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
注意要在SurfaceView的holder加载完毕后再设置捕捉MediaPlayer的画面。否则容易报错。
使用VideoView播放视频的布局文件入下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.myapplication.VideoviewActivity">
<VideoView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/vv_avv"
/>
</LinearLayout>
其中Activity代码十分简单,代码入下
VideoView vv_avv = (VideoView) findViewById(R.id.vv_avv);
vv_avv.setVideoPath("/storage/sdcard1/sister.mp4");
MediaController mediaController = new MediaController(this);
vv_avv.setMediaController(mediaController);
mediaController.setMediaPlayer(vv_avv);