Video MediaPlayer

We can stream media, including video, to a MediaPlayer object using a surface view.

Video MediaPlayer

For example, you could use the following layout:

<RelativeLayout 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:background="#000000"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <SurfaceView
        android:id="@+id/activity_video_surfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/activity_video_imageButton_play"/>

    <Button
        android:id="@+id/activity_video_imageButton_play"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@android:drawable/ic_media_play" />

</RelativeLayout>

We will refer to the SurfaceView in the implementation of the Activity class.

Now in our Activity class, add the following interfaces:

public class VideoActivity extends Activity implements SurfaceHolder.Callback{

Your IDE should prompt you to add these unimplemented methods:

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
}

@Override
public void surfaceCreated(SurfaceHolder arg0) {
//setup
}

@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
}

@Override
public void onPrepared(MediaPlayer mp) {
//start playback
}

In surfaceCreated we must add these code line:

try {
	mMediaPlayer = new MediaPlayer();
	mMediaPlayer.setDisplay(mVidHolder);
	mMediaPlayer.setDataSource(Constants.VID_ADDRESS);
	mMediaPlayer.prepare();
	mMediaPlayer.setOnPreparedListener(this);
	mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
	e.printStackTrace();
}

In surfaceDestroyed we add this:

mMediaPlayer.stop();

Download code

Leave a Reply

Your email address will not be published. Required fields are marked *