Android视频播放

上节课我们讲了安卓MP3播放,现在我们学习视频播放,遗憾的是目前MediaPlayer只能播放3gp的视频格式,其他需要相应解码器。

视频中的渲染需要一个我们还没有学习过的组件SurfaceView,以及android.view.SurfaceHolder;对其实时渲染

先看主配置文件.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    
    tools:context=".MediaDemo" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageButton
            android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="start"
            android:src="@drawable/start" />

        <ImageButton
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="stop"
            android:src="@drawable/stop" />

    </LinearLayout>

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

主Activity代码:

public class MediaDemo extends Activity {

	MediaPlayer mediaplayer;
	SurfaceView surfaceview;
	SurfaceHolder surfaceviewholder;
	Context context;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_media_demo);
		surfaceview=(SurfaceView)super.findViewById(R.id.surfaceView);
		this.context=MediaDemo.this;
		this.surfaceviewholder=surfaceview.getHolder();
		this.surfaceviewholder.setType(surfaceviewholder.SURFACE_TYPE_PUSH_BUFFERS);
		this.mediaplayer=new MediaPlayer();
		try {
			this.mediaplayer.setDataSource("/sdcard/ee.3gp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void start(View v){
		this.mediaplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		this.mediaplayer.setDisplay(surfaceviewholder);
		try {
			this.mediaplayer.prepare();
			this.mediaplayer.start();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	public void stop(View v){
		this.mediaplayer.stop();
		
	}

}

实现效果如下:


Android视频播放
 

相关推荐