2015年3月31日 星期二

[Android] The basic concept of using MediaPlayer

If we want to play music or multimedia files, the simple way is to use MediaPlayer.
We can use in this way:

private MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/sdcard/test.mp3");//Set the source
mp.prepare();
mp.start();

If the source is from internet streaming, it can also support it.
For example:
mp.setDataSource("rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov");
MediaPlayer support HTTP and RTSP streaming both.

If we use MediaPlayer to play video files, we will need to incorporate SurfaceView.
Notice that new MediaPlayer() must be declared in surfaceCreated(), as shown below:
@Overridepublic void surfaceCreated(SurfaceHolder sh) {
         mp= new MediaPlayer();
         mp.setDisplay(surfaceHolder);   
         mp.setOnPreparedListener(this);      
    }
@Override
     public void surfaceDestroyed(SurfaceHolder arg0) {
         mp.release();
     }

@Override
public void onPrepared(MediaPlayer mp) {
        mp.start();
     }
If we have one button to control the play action, we can add the codes below in onClick() event of that button.
mp.setDataSource("your source path");
mp.prepareAsync();  

MediaPlayer can support many formats, such as MP3,MPEG2,H.264,3gp....

沒有留言:

張貼留言