Introduction to this section:

This section brings the MediaPlayer in Android multimedia. Through this API, we can play audio and video. This class is an important component in the Android multimedia framework. Through this class, we can obtain, decode, and play audio and video with minimal steps. It supports three different media sources:

  • Local resources
  • Internal URI, for example, you can obtain it through ContentResolver
  • External URL (stream)

For the list of media formats supported by Android, see:Supported Media FormatsDocumentation

In this section, we will use MediaPlayer to write a simple example of playing audio and video!

Official API documentation:MediaPlayer


1. Detailed Explanation of Related Methods


1) Obtaining a MediaPlayer instance:

You candirectly use newor callcreatemethod to create:

MediaPlayer mp = new MediaPlayer();
MediaPlayer mp = MediaPlayer.create(this, R.raw.test);  //无需再调用setDataSource

In addition, create also has the following form:create(Context context, Uri uri, SurfaceHolder holder)Create a multimedia player through a Uri and a specified SurfaceHolder [abstract class]


2) Setting the playback file:

//①raw下的资源:
MediaPlayer.create(this, R.raw.test);

//②本地文件路径:
mp.setDataSource("/sdcard/test.mp3");

//③网络URL文件:
mp.setDataSource("http://www.xxx.com/music/test.mp3");

In addition, the setDataSource() method has several overloads, and one of them has a parameter of type FileDescriptor. When using this API, you need to put the file in the assets folder, which is at the same level as the res folder, and then use the following code to set the DataSource:

AssetFileDescriptor fileDescriptor = getAssets().openFd("rain.mp3");
m_mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());

3) Other methods

  • getCurrentPosition(): Get the current playback position
  • getDuration(): Get the duration of the file
  • getVideoHeight(): Get the video height
  • getVideoWidth(): Get the video width
  • isLooping(): Whether it is looping
  • isPlaying(): Whether it is currently playing
  • pause(): Pause
  • prepare(): Prepare (synchronous)
  • prepareAsync(): Prepare (asynchronous)
  • release(): Release the MediaPlayer object
  • reset(): Reset the MediaPlayer object
  • seekTo(int msec): Specify the playback position (time in milliseconds)
  • setAudioStreamType(int streamtype): Specify the type of streaming media
  • setDisplay(SurfaceHolder sh): Set to use SurfaceHolder to display multimedia
  • setLooping(boolean looping): Set whether to loop playback
  • setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener): Buffering listener for network streaming media
  • setOnCompletionListener(MediaPlayer.OnCompletionListener listener): Playback completion listener for network streaming media
  • setOnErrorListener(MediaPlayer.OnErrorListener listener): Set error message listener
  • setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener): Video size listener
  • setScreenOnWhilePlaying(boolean screenOn): Set whether to use SurfaceHolder for display
  • setVolume(float leftVolume, float rightVolume): Set volume
  • start(): Start playback
  • stop(): Stop playback

2. Code Examples

Example 1: Using MediaPlayer to play audio:

Screenshot of the running result:

Key code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button btn_play;
    private Button btn_pause;
    private Button btn_stop;
    private MediaPlayer mPlayer = null;
    private boolean isRelease = true;   //判断是否MediaPlayer是否释放的标志

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        btn_play = (Button) findViewById(R.id.btn_play);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_play.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_play:
                if(isRelease){
                    mPlayer = MediaPlayer.create(this,R.raw.fly);
                    isRelease = false;
                }
                mPlayer.start();   //开始播放
                btn_play.setEnabled(false);
                btn_pause.setEnabled(true);
                btn_stop.setEnabled(true);
                break;
            case R.id.btn_pause:
                mPlayer.pause();     //停止播放
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(false);
                break;
            case R.id.btn_stop:
                mPlayer.reset();     //重置MediaPlayer
                mPlayer.release();   //释放MediaPlayer
                isRelease = true;
                btn_play.setEnabled(true);
                btn_pause.setEnabled(false);
                btn_stop.setEnabled(false);
                break;
        }
    }
}

Notes:

What is being played is an audio file in the res/raw directory. The MediaPlayer is created via the create method, and before the first start of playback, there is no need to call prepare(). If it is constructed using the constructor method, then you need to call prepare() once. Also, here is the sample code from the official documentation for playing audio through the other two approaches:

Local URI:

Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();

External URL:

String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();

Note: If you play an online audio file from a URL as a stream, the file must support progressive download.


Example 2: Using MediaPlayer to play video

MediaPlayer is mainly used to play audio and does not provide an image output interface, so we need to use other components to display the image output of MediaPlayer playback. We can useSurfaceViewto display it. Next, we will use SurfaceView to write an example of video playback:

Screenshot of the running result:

Implementation code:

Layout file:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">

    <SurfaceView
        android:id="@+id/sfv_show"
        android:layout_width="match_parent"
        android:layout_height="300dp" />

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始" />

    <Button
        android:id="@+id/btn_pause"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="暂停 " />

    <Button
        android:id="@+id/btn_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="终止" />
    
</LinearLayout>

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener, SurfaceHolder.Callback {

    private MediaPlayer mPlayer = null;
    private SurfaceView sfv_show;
    private SurfaceHolder surfaceHolder;
    private Button btn_start;
    private Button btn_pause;
    private Button btn_stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        sfv_show = (SurfaceView) findViewById(R.id.sfv_show);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_start.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);

        //初始化SurfaceHolder类,SurfaceView的控制器
        surfaceHolder = sfv_show.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setFixedSize(320, 220);   //显示的分辨率,不设置为视频默认

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                mPlayer.start();
                break;
            case R.id.btn_pause:
                mPlayer.pause();
                break;
            case R.id.btn_stop:
                mPlayer.stop();
                break;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mPlayer = MediaPlayer.create(MainActivity.this, R.raw.lesson);
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDisplay(surfaceHolder);    //设置显示视频显示在SurfaceView上
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer.isPlaying()) {
            mPlayer.stop();
        }
        mPlayer.release();
    }
}

The code is very simple. The layout has a SurfaceView, then we call getHolder to obtain a SurfaceHolder object. Here we complete the SurfaceView-related settings, set the display resolution and a Callback interface, and override the three methods for when the SurfaceView is created, changed, and destroyed! Then buttons control playback and pause, that's all~


Example 3: Using VideoView to play video

Besides using MediaPlayer + SurfaceView to play video, we can also use VideoView to directly play video. With a slight modification, we can achieve video playback! The running effect is the same as above, so I won't post it. Let's go straight to the code!

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private VideoView videoView;
    private Button btn_start;
    private Button btn_pause;
    private Button btn_stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }
    
    private void bindViews() {
        videoView = (VideoView) findViewById(R.id.videoView);
        btn_start = (Button) findViewById(R.id.btn_start);
        btn_pause = (Button) findViewById(R.id.btn_pause);
        btn_stop = (Button) findViewById(R.id.btn_stop);

        btn_start.setOnClickListener(this);
        btn_pause.setOnClickListener(this);
        btn_stop.setOnClickListener(this);
        
        //根据文件路径播放
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            videoView.setVideoPath(Environment.getExternalStorageDirectory() + "/lesson.mp4");
        }

        //读取放在raw目录下的文件
        //videoView.setVideoURI(Uri.parse("android.resource://com.jay.videoviewdemo/" + R.raw.lesson));
        videoView.setMediaController(new MediaController(this));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                videoView.start();
                break;
            case R.id.btn_pause:
                videoView.pause();
                break;
            case R.id.btn_stop:
                videoView.stopPlayback();
                break;
        }
    }
}

The code is very simple, so no explanation needed~ If you have questions, just download a demo and run it~


3. Download sample code for this section:

MediaPlayerDemo.zip

MediaPlayerDemo2.zip

VideoViewDemo.zip


Summary of this section:

Okay, this section briefly introduced how to use MediaPlayer to play audio and combined with SurfaceView to play video. Finally, we also wrote an example of playing video with VideoView. These are all very simple usages~ I believe everyone will find it very easy to learn. Well, thank you~