Android error-MediaPlayer usage: Media Player called in state *, androidmediaplayer
When using Media Player, let's take a look at several issues.
The usage will not be mentioned. It is best to refer to this figure of mediaPlayer when using it.
The first error is Media Player called in state 8.
This is because there is no prepare before start is called, because I used
mediaPlayer = MediaPlayer.create(context, R.raw.notice);
Initialize the player. This API description
As long as the player is successfully returned, you do not need to go to prepare again. However, when I call stop and start multiple times, the above error occurs,
We can also see from the comparison chart that if you use stop for pause, you must re-prepare before start. Otherwise, the Media Player called in state 8 error is reported.
If pause is suspended, start directly without prepare.
The second error is Media Player called in state 0.
This error is caused
public void play(){try {mediaPlayer.prepare();} catch (IllegalStateException e) {e.printStackTrace();}mediaPlayer.start();
}
Change to the following:
public void play(){try {mediaPlayer.setOnPreparedListener(preparedListener);mediaPlayer.prepareAsync();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();}}OnPreparedListener preparedListener = new OnPreparedListener() {@Overridepublic void onPrepared(MediaPlayer mp) {mediaPlayer.start();}};
At the beginning, I realized that I directly went to start after completing the prepare. However, at this time, the prepare may not be successful, so I reported the above error.
Then, a prepareAsync called in state 8 error occurs.
This solution adds a line of code based on the previous one to ensure that the player has stopped before prepare.
public void play() {try {if(mediaPlayer !=null){mediaPlayer.stop();}mediaPlayer.setOnPreparedListener(preparedListener);mediaPlayer.prepareAsync();} catch (IllegalStateException e) {e.printStackTrace();}currentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);if (currentVolumn < maxVolumn) {am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolumn, 0);}}
Author: jason0539
Weibo: http://weibo.com/2553717707
Blog: http://blog.csdn.net/jason0539 (reprinted please explain the source)