Android MediaPlayer basis Introduction

This link: Android MediaPlayer basis Introduction

MediaPlayer simply describes the basic concepts of the state, and the common method listener.

What is MediaPlayer

MediaPlayer class can be used to play audio and video files, or an audio stream. Developers can use it to play local audio, network or online audio.

MediaPlayer packet belongs.

MediaPlayer state

Playback control by the state machine. In everyday life, we have a common state audio playback, pause, stop, cushion and so on.
    MediaPlayer state following categories:

  • Idle
  • End
  • Error
  • Initialized
  • Preparing
  • Prepared
  • Started
  • Stopped
  • Paused
  • PlaybackCompleted

Refer to the official legend switching state.
    Here explain a little state transition picture. Ellipse represents the state MediaPlayer might stay. The arrows indicate method calls between the oval, the direction of the state switching. Single arrow indicates synchronous method call, double arrow asynchronous calls.

From FIG path and a state switching method involved we can see.

Idle and End state

When a new MediaPlayer or call the reset method, the current MediaPlayer will be in the Idle state. After calling the release, it will be in End state. State between these two states can be seen as the life cycle of MediaPlayer object.

There are some subtle differences between the new call and reset the creation MediaPlayer MediaPlayer.
    In both cases, the Idle state, calling getCurrentPosition (), getDuration (), getVideoHeight (), getVideoWidth (), setAudioAttributes (, setLooping (boolean), setVolume (float, float), pause () , start (), stop (), seekTo (long, int), prepare () or prepareAsync () method will throw an error if a new instance of MediaPlayer, not the callback OnErrorListener.onError (); but if it is reset after MediaPlayer, calls back OnErrorListener.onError () and converted to the Error state.

If the MediaPlayer object is no longer used, immediately call release () method to release the resources occupied by the internal player. These resources may be unique, such as hardware acceleration components. If the call fails release, it may cause a series of MediaPlayer instance fails. When MediaPlayer in End state, it can not be transferred to the other state.

a new MediaPlayer, the Idle state. If the create method used to create an instance, in the Prepared state when created.

An error occurred

Some situations may make MediaPlayer operation fails, such as audio and video formats are not supported, high-resolution, network timeouts and so on.
    Therefore, error handling and recovery in these circumstances is very important. Sometimes MediaPlayer programming errors can lead to errors.
    Developers can set error listener setOnErrorListener ( When an error occurs, it will call OnErrorListener.onError () method for the user to achieve.

With or without setting the listener, when an error occurs MediaPlayer will enter the Error state.

In order to reuse the same MediaPlayer object, you can reset () method to recover it from the Error state to the Idle state.
    Set error listener OnErrorListener is a good programming practice. Developers can listen to the playback engine of error notification.
    Sometimes IllegalStateException is thrown, such as in an error state call prepare (), prepareAsync () method, or setDataSource method.

Setting audio setDataSource

Call setDataSource (, or setDataSource (java.lang.String), or setDataSource (android.content.Context,, or setDataSource (, long, long), or setDataSource ( may MediaPlayer from Idle state to state Initialized.
    If the state outside the Idle state called setDataSource (), it will throw an IllegalStateException.
    Developers should be aware of setDataSource method throws IllegalArgumentException and IOException anomaly.

Must play audio before the Prepared state

MediaPlayer must be in the Prepared state before start playing the audio.

MediaPlayer synchronous and asynchronous two ways to enter the Prepared state. If it is an asynchronous manner, we will first go to the Preparing state, and then go to the Prepared state.
    OnPreparedListener of onPrepared set before when the preparation is completed, the internal playback engine calls back to the user () method.

Developers must be noted that, Preparing state is a transition state (transient state).

When Prepared in the state, the volume can be set, the screen is on, circulating the like playback method corresponding.

Start playing

Play audio you must call the start () method. Start () call returns after the success, MediaPlayer in Started state.
    May determine whether the current state Started by isPlaying ().

If the developer is set OnBufferingUpdateListener, Android player internal buffer information passed outwardly.

If the current method in the Started state, then call start () has no effect.

Pause playback and resume playback

Audio playback can be paused and continued to play, you can also adjust the position played. To pause audio playback through the pause () method.
    After a successful call to pause () method, MediaPlayer into the Paused state.
    It should be noted, MediaPlayer handover between asynchronous and Paused state Started state. When playing audio streams, this conversion process may take a few seconds.

When MediaPlayer pause, start () method can continue playing from where it was paused. After a successful call to the start method will enter the Started state.

While in Paused state, call the pause () method has no effect.


Call the stop () method to let MediaPlayer from Started, Paused, Prepared or PlaybackCompleted state enters the Stopped state.

Later in the Stopped state, you must first call the prepare () or prepareAsync () into the Prepared state, in order to play audio.

While in the Stopped state, call the stop () method has no effect.

Adjust the playback position

Call seekTo (long, int) to adjust the playback position.

seekTo (long, int) is an asynchronous method, although it can return immediately, but the actual position adjustment may consume some time, especially when playing audio stream. When the actual play position adjustment, internal player will callback OnSeekComplete.onSeekComplete developer set ().

In Prepared, Paused and PlaybackCompleted state, can call seekTo method.

Current playback position can be acquired by the getCurrentPosition () method. Developers can learn the progress currently playing, and so on.

Finished playing

After the completion of audio playback, finished playing.

If you call setLooping (boolean) is true, MediaPlayer will stay in the Started state.

If setLooping is false, the player will call OnCompletion.onCompletion internal developers set (), and enter PlaybackCompleted state.

While in PlaybackCompleted state, call the start () method can play audio from the beginning.

Common Listener

Developers can set some listeners, listening MediaPlayer status, error events, and so on. Developers should create MediaPlayer and set listener in the same thread.

setOnPreparedListener (
    MediaPlayer ready to listen. Generally used in conjunction with prepareAsync.

setOnVideoSizeChangedListener (
    Learn to listen when the video size or video size change.

setOnSeekCompleteListener (
    Listening position adjustment is completed.

setOnCompletionListener (
    Finished playing.

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mediaPlayer) {
        // 当前播放完毕

setOnBufferingUpdateListener (
    Monitor the progress of the buffer. Common network when playing audio.

Buffer listener OnBufferingUpdateListener

    mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            // 例如在这里更新UI

setOnInfoListener (
    Monitor general information or warning messages.

setOnErrorListener (
    Monitor error messages. When an error occurs, the error can be handled here.

mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
        LogUtil.e(TAG_PREFIX + " onERR i = " + i + " i1 = " + i1);
        return true; // 返回true表示在此处理错误,不会回调onCompletion

Note that the return value of onError. You can choose their own processing error.

         * @return True if the method handled the error, false if it didn't.
         * Returning false, or not having an OnErrorListener at all, will
         * cause the OnCompletionListener to be called.
        boolean onError(MediaPlayer mp, int what, int extra);

Permissions required

Manifest.permission.INTERNET permissions required when playing audio network.

Leave a Reply