We can stream media, including video, to a MediaPlayer object using a surface view.
For example, you could use the following layout:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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:
1 | public class VideoActivity extends Activity implements SurfaceHolder.Callback{ |
Your IDE should prompt you to add these unimplemented methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | @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:
1 2 3 4 5 6 7 8 9 10 | 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:
1 | mMediaPlayer.stop(); |