Media Player called in state 0, error (-38,0)
You need to call mediaPlayer.start()
in the onPrepared
method by using a listener.
You are getting this error because you are calling mediaPlayer.start()
before it has reached the prepared state.
Here is how you can do it :
mp.setDataSource(url);
mp.setOnPreparedListener(this);
mp.prepareAsync();
public void onPrepared(MediaPlayer player) {
player.start();
}
It seems like Error -38 means a state-exception (as the error-message indicates). For example if you call start()
, before the song was ready, or when you call pause()
, even if the song isn't playing at all.
To fix this issue check the state of the mediaPlayer before calling the methods. For example:
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
Additionally, the MediaPlayer is sending event-messages. Even if you do not need the prepared-event (although it would be a good idea to not start the playback before this event was fired) you must set a callback-listener. This also holds true for the OnErrorListener
, OnCompletionListener
, OnPreparedListener
and OnSeekCompletedListener
(if you call the seek method).
Listeners can be attached simply by
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
// Do something. For example: playButton.setEnabled(true);
}
});
I got this error when I was trying to get the current position (MediaPlayer.getCurrentPosition()) of media player when it wasn't in the prepared stated. I got around this by Keeping track of its state and only calling the getCurrentPosition() method after onPreparedListener is called.