Introduction to Android MediaPlayer Basics

Link to this article: introduction to Android MediaPlayer Foundation

Briefly introduce the basic concept, status, common methods and listeners of mediaplayer.

The mediaplayer class can be used to play audio and video files or audio streams. Developers can use it to play local audio or online audio.

Mediaplayer belongs to the android.media package.

The playback control is controlled by the state machine. In daily life, our common audio states are playing, pause, stop, buffer and so on. Mediaplayer has the following statuses:

Refer to the official legend for status switching. Here is a little explanation of the state transition picture. The ellipse represents the state that mediaplayer may stay in. The arrow between the ellipses indicates the direction of method call and state switching. A single arrow indicates synchronous method invocation, and a double arrow indicates asynchronous invocation.

From the figure, we can see the path of state switching and the methods involved.

When a new mediaplayer is created or the reset method is called, the current mediaplayer will be in idle state. After release is called, it will be in the end state. The state between these two states can be regarded as the life cycle of the mediaplayer object.

There are some subtle differences between the newly created mediaplayer and the mediaplayer calling reset. Both cases are in idle state. Calling getcurrentposition(), getduration(), getvideoheight(), getvideowidth(), setaudioattributes (Android. Media. Audioattributes), setlooping (Boolean), SetVolume (float, float), pause(), start(), stop(), seekto (long, int), prepare() or prepareasync() methods will throw errors. If it is a newly instantiated mediaplayer, Does not callback onerrorlistener. Onerror(); However, if it is mediaplayer after reset, it will call back onerrorlistener. Onerror() and transition to error state.

If the mediaplayer object is no longer used, immediately call the release () method to release the resources occupied by the internal player. These resources may be unique, such as hardware acceleration components. If the call to release fails, a series of mediaplayer instances may fail. When mediaplayer is in the end state, it cannot be transferred to other states.

New a mediaplayer in idle state. If you use the Create method to create an instance, it will be in the prepared state when the creation is completed.

Mediaplayer may fail in some situations, such as unsupported audio and video formats, high resolution, network timeout, etc. Therefore, error handling and recovery are very important in these cases. Sometimes programming errors can also cause mediaplayer operation errors. Developers can set the error listener setonerrorlistener (Android. Media. Mediaplayer. Onerrorlistener). When an error occurs, the user implemented onerrorlistener. Onerror() method is called.

No matter whether the listener is set or not, mediaplayer will enter the error state when an error occurs.

To reuse the same mediaplayer object, you can use the reset () method to restore it from the error state to the idle state. Setting the error listener onerrorlistener is a good programming habit. Developers can listen to the error notification of the playback engine. Sometimes an IllegalStateException is thrown. For example, the prepare() prepareasync() method or the setdatasource method is called in the wrong state.

Calling setdatasource (Java. Io. Filedescriptor), or setdatasource (Java. Lang. string), or setdatasource (Android. Content. Context, Android. Net. URI), or setdatasource (Java. Io. Filedescriptor, long, long), or setdatasource (Android. Media. Mediadatasource) can change the state of mediaplayer from idle to initialized. If setdatasource() is called in a state other than the idle state, an IllegalStateException will be thrown. Developers should pay attention to the illegalargumentexception and IOException thrown by the setdatasource method.

Mediaplayer must be in prepared state before starting playing audio.

Mediaplayer can enter the prepared state in two ways: synchronous and asynchronous. If it is asynchronous, it will go to the preparing state first, and then to the prepared state. When the preparation is completed, the internal playback engine will call back the onpreparedlistener's onprepared () method set by the user.

Developers must note that the preparing state is a transient state.

When in the prepared state, you can set the volume through corresponding methods, the screen is always on, playback cycle, etc.

The start () method must be called to play audio. After calling start() to return success, mediaplayer is in the started state. You can use isplaying() to determine whether you are currently in the started state.

If the developer sets onbufferingupdatelistener, the Android internal player will transfer buffer information to the outside.

If you are currently in the started state, calling the start () method again has no effect.

The audio can be paused and continued, or the playback position can be adjusted. Pause the audio playback through the pause () method. After successfully calling the pause() method, mediaplayer enters the paused state. It should be noted that mediaplayer switches between the started state and the paused state asynchronously. When playing an audio stream, this conversion process may take a few seconds.

When mediaplayer is paused, the start () method can continue playing from the paused position. After successfully calling the start method, it will enter the started state.

When in the paused state, calling the pause () method has no effect.

Call the stop () method to make mediaplayer enter the stopped state from the started, paused, prepared or playbackcompleted state.

In the stopped state, you must call prepare() or prepareasync() to enter the prepared state before playing audio.

When in the stopped state, calling the stop () method has no effect.

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

Seekto (long, int) is an asynchronous method. Although it can return immediately, the actual position adjustment may take some time, especially when playing an audio stream. After the actual playback position is adjusted, the internal player will call back onseekcomplete. Onseekcomplete() set by the developer.

The seekto method can be called in the prepared, paused and playbackcompleted states.

You can get the current playback position through the getcurrentposition () method. Developers can know the current playback progress and so on.

After the audio playback is completed, the playback is completed.

If the calling setlooping (Boolean) is true, mediaplayer will stay in the started state.

If setlooping is false, the internal player will call oncompletion. Oncompletion() set by the developer and enter the playbackcompleted state.

When in the playbackcompleted state, you can play the audio from the beginning by calling the start () method.

Developers can set up some listeners to listen to mediaplayer status, error events and so on. Developers should create mediaplayer and set listener in the same thread.

Setonpreparedlistener (Android. Media. Mediaplayer. Onpreparedlistener) listens. Mediaplayer preparation is complete. It is generally used with prepareasync.

Setonvideosizechangedlistener (Android. Media. Mediaplayer. Onvideosizechangedlistener) knows the video size or the listening when the video size changes.

Setonseekcompletelistener (Android. Media. Mediaplayer. Onseekcompletelistener) listens to the completion of position adjustment.

Setoncompletionlistener (Android. Media. Mediaplayer. Oncompletionlistener) playback is complete.

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

Setonbufferingupdatelistener (Android. Media. Mediaplayer. Onbufferingupdatelistener) listens for buffering progress. Commonly used when playing network audio.

Buffer listener onbufferingupdatelistener

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

Setoninfolistener (Android. Media. Mediaplayer. Oninfolistener) listens for general information or warning information.

Setonerrorlistener (Android. Media. Mediaplayer. Onerrorlistener) listens for error messages. When an error occurs, it can be handled here.

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

Note the return value of onerror. You can choose to handle the error yourself.

         * @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);

Manifest.permission.internet permission is required when playing network audio.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>