Learner Learner - 2 months ago 19
Android Question

IllegalStateException in MediaPlayer set datasource method

I'm using the following code in my

onCompletion
listener of
MediaPlayer
where I'm repeating the current song.

if (isRepeat) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
try {
mMediaPlayer.setDataSource(MainActivity.localTrackList.get(MainActivity.currentOffset).getPath());
mMediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}


But I'm getting the following error Message,

at android.media.MediaPlayer._setDataSource(Native Method)
09-15 09:05:19.884 12545-12545/ W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1115)
09-15 09:05:19.884 12545-12545/ W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1100)
09-15 09:05:19.884 12545-12545/ W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1079)
09-15 09:05:19.884 12545-12545/ W/System.err: at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1028)


How can I be able to sort this out?

Answer

MediaPlayer.setDataSource() is only useful when the MediaPlayer's state is Idle, you called this method in onCompletion so the android system gave you a IllStateException. mMediaPlayer.isPlaying() seems always return false in onCompletion method.

Actually you do not need to setDataSource again, you can just call MediaPlayer.start() to play the data from start.

See this state diagram:

Comments