Media player throwing illegal state exception

Issue

I’m trying to play a song but Media player is throwing IllegalState exception.This is how i’m trying to play a song

private fun playSong(songPath: String) {
        if (mediaPlayer ! null) {
            if (mediaPlayer!!.isPlaying) {
                stopPlay()
                mediaPlayer!!.setDataSource(songPath)
                mediaPlayer!!.setOnPreparedListener(this)
                mediaPlayer!!.setOnCompletionListener(this)
                mediaPlayer!!.prepareAsync()
            } else {
                mediaPlayer!!.setDataSource(songPath)
                mediaPlayer!!.setOnPreparedListener(this)
                mediaPlayer!!.setOnCompletionListener(this)
                mediaPlayer!!.prepareAsync()
            }
        } else {
            mediaPlayer  MediaPlayer()
            mediaPlayer!!.setDataSource(songPath)
            mediaPlayer!!.setOnPreparedListener(this)
            mediaPlayer!!.setOnCompletionListener(this)
            mediaPlayer!!.prepareAsync()
        }

and this is how i’m stoping play

private fun stopPlay() {
        mediaPlayer!!.pause()
        mediaPlayer!!.stop()
    }

exception thrown by media player is

java.lang.IllegalStateException
        at android.media.MediaPlayer._setDataSource(Native Method)

Solution

You should call reset() before setDataSource when you are re-using the same media player instance.

   if (mediaPlayer ! null) {
        if (mediaPlayer!!.isPlaying) {
            stopPlay()
            mediaPlayer!!.reset()
            mediaPlayer!!.setDataSource(songPath)
            mediaPlayer!!.setOnPreparedListener(this)
            mediaPlayer!!.setOnCompletionListener(this)
            mediaPlayer!!.prepareAsync()
        } else {
            mediaPlayer!!.reset()
            mediaPlayer!!.setDataSource(songPath)
            mediaPlayer!!.setOnPreparedListener(this)
            mediaPlayer!!.setOnCompletionListener(this)
            mediaPlayer!!.prepareAsync()
        }
    } else {
        mediaPlayer  MediaPlayer()
        mediaPlayer!!.setDataSource(songPath)
        mediaPlayer!!.setOnPreparedListener(this)
        mediaPlayer!!.setOnCompletionListener(this)
        mediaPlayer!!.prepareAsync()
    }

Answered By – Nitin Jain

Leave a Comment