Android audio and video development - MediaPlayer audio and video playback introduction

In Android multimedia - MediaPlayer, we can use this API to 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 the smallest steps.
It supports three different media sources:

  • local resources
  • Internal URI, for example, you can get it through ContentResolver
  • List of media formats supported by external URLs (streams) for Android

1. Detailed explanation of related methods

1) Get a MediaPlayer instance:

It can be created directly by new or by calling the create method:

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

In addition, create has such a form: create(Context context, Uri uri, SurfaceHolder holder) creates a multimedia player through Uri and specified SurfaceHolder [abstract class].

2) Set 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, there are multiple setDataSource() methods, which have such a type of parameter: FileDescriptor. When using this API, you need to put the file in the assets folder 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 time of the file
  • getVideoHeight (): get video height
  • getVideoWidth (): get video width
  • isLooping (): whether to loop
  • isPlaying (): whether it is playing
  • pause (): pause
  • prepare (): prepare (synchronous)
  • prepareAsync (): prepare (asynchronous)
  • release() : Release the MediaPlayer object
  • reset (): Reset the MediaPlayer object
  • seekTo(int msec) : specifies the position to play (time in milliseconds)
  • setAudioStreamType(int streamtype) : Specifies the type of streaming media
  • setDisplay(SurfaceHolder sh) : Set SurfaceHolder to display multimedia
  • setLooping(boolean looping) : Set whether to loop
  • setOnBufferingUpdateListener(MediaPlayer.OnBufferingUpdateListener listener) : Buffering monitoring of network streaming media
  • setOnCompletionListener(MediaPlayer.OnCompletionListener listener) : Listen to the end of network streaming media playback
  • setOnErrorListener(MediaPlayer.OnErrorListener listener) : Set error message listening
  • setOnVideoSizeChangedListener(MediaPlayer.OnVideoSizeChangedListener listener) : Video size monitoring
  • setScreenOnWhilePlaying(boolean screenOn) : Set whether to use SurfaceHolder display
  • setVolume(float leftVolume, float rightVolume) : set the volume
  • start (): start playing
  • stop (): stop playing

If you want the full version of Android audio and video learning materials, please click to get it for free

2. Use the code example

Example 1: Use MediaPlayer to play audio:

Running effect diagram :

insert image description here

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;
        }
    }
}

Precautions:

The audio files in the res/raw directory are played, and the create method is called to create a MediaPlayer. There is no need to call prepare() before starting playback for the first time. If it is constructed using the constructor, you need to call the prepare() method once. ! In addition, post the sample code for playing audio from the other two ways in the official document:

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 stream an online audio file via a URL, the file must be progressively downloadable

Example 2: Play video with MediaPlayer

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 played by MediaPlayer. We can use SurfaceView to display it. Below we use SurfaceView to write an example of video playback:

Running effect diagram :

insert image description here

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. There is a SurfaceView in the layout, and then call getHolder to obtain a SurfaceHolder object. Here, the SurfaceView-related settings are completed, the display resolution and a Callback interface are set, and the SurfaceView is rewritten when it is created, when it changes, and when it is destroyed. The three methods! Then the buttons control play and pause.

Example 3: Use VideoView to play video

In addition to using MediaPlayer + SurfaceView to play videos, we can also use VideoView to play videos directly. We can achieve video playback with a little change! The running effect is consistent with the above, so I won’t post it, just upload the code directly!

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;
        }
    }
}

If you need the full version of Android audio and video learning files, please scan and get free
insert image description here

Guess you like

Origin blog.csdn.net/m0_71506521/article/details/130319360