Link to this article: Introduction to Android MediaPlayer basics
MediaPlayer introduces the basic concepts, states, common methods and listeners of MediaPlayer.
What is the MediaPlayer
The MediaPlayer class can be used to play audio and video files, or audio streams. Developers can use it to play local audio, as well as online audio.
MediaPlayer is part of the Android. media package.
The state of the MediaPlayer
The playback control is controlled by the state machine. In daily life, our common audio states are play, pause, stop, buffer and so on. MediaPlayer has the following states:
- Idle
- End
- Error
- Initialized
- Preparing
- Prepared
- Started
- Stopped
- Paused
- PlaybackCompleted
Refer to the official legend for state switching. Here’s a little explanation of the state transition picture. The ellipse represents the state in which MediaPlayer can stay. The arrows between the ellipses indicate the direction of the method call, state switch. Single arrows indicate synchronous method invocation and double arrows indicate asynchronous invocation.
From the figure we can see the path of state switching and the methods involved.
The status is Idle and End
When a MediaPlayer is new or the reset method is called, the current state of the MediaPlayer is Idle. When WE call release, we’re going to be in the End state. The state between these two states can be thought of as the life cycle of a MediaPlayer object.
There are some subtle differences between the newly created MediaPlayer and the MediaPlayer that calls Reset. Both cases are Idle, Call getCurrentPosition(), getDuration(), getVideoHeight(), getVideoWidth(), setAudioAttributes(android.media.AudioAttributes), setLooping(boolean), setVolume(float, float), pause(), start(), The stop(), seekTo(long, int), prepare(), or prepareAsync() methods all throw an error. If the MediaPlayer is newly instantiated, onErrorListener.onError () is not called; But if the MediaPlayer is reset, onErrorListener.onError () will be called back and changed to the Error state.
If the MediaPlayer object is no longer in use, the release() method is immediately called to release resources occupied by the internal player. These resources may be unique, such as hardware accelerated components. A failure to call release could cause a string of MediaPlayer instances to fail. When MediaPlayer is in the End state, it cannot be moved to another state.
New A MediaPlayer in Idle state. If the instance is created using the create method, it will be in Prepared when it is created.
An error occurred
MediaPlayer can fail in several situations, such as unsupported audio and video formats, high resolution, network timeouts, and so on. Error handling and recovery are therefore very important in these situations. Sometimes programming errors can also cause MediaPlayer to operate incorrectly. Developers can set wrong listeners setOnErrorListener (android. Media. The MediaPlayer. OnErrorListener). When an error occurs, the user-implemented onErrorListener.onError () method is called.
MediaPlayer will enter an Error state when an Error occurs, regardless of whether a listener is set.
To reuse the same MediaPlayer object, use the reset() method to restore it from the Error state to Idle. It is good programming practice to set the error listener OnErrorListener. Developers can listen for error notifications from the playback engine. IllegalStateException is sometimes thrown, such as when the prepare(), prepareAsync(), or setDataSource methods are called in the wrong state.
Set the audio source setDataSource
Call 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) to the state of the MediaPlayer from Idle to the Initialized state. If setDataSource() is called from a state other than Idle, IllegalStateException is thrown. Developers should look out for illegalArgumentExceptions and ioExceptions thrown by the setDataSource method.
You must be in Prepared before playing the audio
MediaPlayer must be Prepared before it can start playing audio.
MediaPlayer can be Prepared either synchronously or asynchronously. In the asynchronous mode, the Preparing state is changed first, and then the Prepared state. When the preparation is complete, the internal playback engine calls back the onPrepared() method of OnPreparedListener that the user set up earlier.
It is important to note that the Preparing state is a transient state.
In Prepared, you can set the volume, keep the screen on, and play a loop.
Start playing
The start() method must be called to play audio. MediaPlayer is in the Started state after the call to start() returns success. You can use isPlaying() to determine if the current state is Started.
If developers set up OnBufferingUpdateListener, inside the Android player will message buffer outward.
If the current state is Started, calling the start() method has no effect.
Pause and resume playing
Audio can be paused and resumed, and the position of playback can be adjusted. Pause () to pause audio playback. After a successful call to pause(), MediaPlayer enters Paused state. It should be noted that MediaPlayer switches between the Started and Paused states asynchronously. When playing an audio stream, this conversion process may take a few seconds.
When MediaPlayer is paused, the start() method can resume playing from where it was paused. The Started state is entered after a successful call to the start method.
Paused () has no effect when Paused.
stop
Call the stop() method to make MediaPlayer go to Stopped from the Started, Paused, Prepared, or PlaybackCompleted states.
In the Stopped state, you must call prepare() or prepareAsync() to prepare before playing the audio.
When in the Stopped state, calling stop() has no effect.
Adjust playback position
Call seekTo(long, int) to adjust the playback position.
SeekTo (Long, int) is an asynchronous method, and while it returns immediately, the actual position adjustment can take a while, especially when playing an audio stream. After the actual position adjustment, internal player will callback developers set OnSeekComplete. OnSeekComplete ().
The seekTo method can be called in the Prepared, Paused, and PlaybackCompleted states.
You can get the current play position by using the getCurrentPosition() method. Developers can see the progress of the current play and so on.
Was over
After the audio is played, the audio is played.
If setLooping(Boolean) is true, MediaPlayer will remain in the Started state.
If setLooping to false, the internal player will call developers set OnCompletion. OnCompletion (), and enter the PlaybackCompleted state.
When in the PlaybackCompleted state, the start() method is called to play the audio from the beginning.
Common listener
Developers can set up listeners to listen for MediaPlayer status, error events, and so on. Developers should create MediaPlayer and set listeners in the same thread.
SetOnPreparedListener (android. Media. The MediaPlayer. OnPreparedListener) to monitor MediaPlayer to complete. It is generally used in conjunction with prepareAsync.
SetOnVideoSizeChangedListener (android. Media. The MediaPlayer. OnVideoSizeChangedListener) about video or video size is changed to the size of the monitor.
SetOnSeekCompleteListener (android. Media. The MediaPlayer. OnSeekCompleteListener) listening to adjust position.
SetOnCompletionListener (android. Media. The MediaPlayer. OnCompletionListener) play.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
// The current playback is complete}});Copy the code
SetOnBufferingUpdateListener (android. Media. The MediaPlayer. OnBufferingUpdateListener) to monitor buffer progress. This is often used when playing network audio.
Buffer listener OnBufferingUpdateListener
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// For example, update UI here}});Copy the code
SetOnInfoListener (android. Media. The MediaPlayer. OnInfoListener) listening to the general information or warnings.
SetOnErrorListener (android. Media. The MediaPlayer. OnErrorListener) listening to the wrong information. This is where errors can be handled when they occur.
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; // Returning true means that the error is handled here and onCompletion is not called back}});Copy the code
Notice 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);
Copy the code
Required permissions
Audio broadcast networks need to Manifest. Permission. INTERNET access.