Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalStateException in MediaPlayer

Here is my code

if (player != null) {
    if(player.isPlaying()){
        player.pause();
        player.stop();
    }
    player.release();
}

and here is error

FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.mindefy.sindhipathshala.RecViewAdapter.mediafileRelease(RecViewAdapter.java:234)
at com.mindefy.sindhipathshala.SectionFruits.onBackPressed(SectionFruits.java:252)

I am a beginner in Android and i am very confused with the lifecycle of a MediaPlayer.

This is a function in an adapter that is called from onBackPressed() function of another Activity. player is a class variable.

I am releasing this MediaPlayer in same file as

public void onClick(View v) {
    try {
        if (player != null) {
            player.stop();
            player.release();
        }
    } catch (Exception e) {
    }
    player = MediaPlayer.create(activityContext, soundId);
    player.start();
}
like image 850
Shunan Avatar asked Jul 02 '16 08:07

Shunan


2 Answers

The problem is you don't keep track of the state of your MediaPlayer instance.

Before calling isPlaying() you only perform a null value check, although player can still be released (but not null).

Calling isPlaying() on a released MediaPlayer instance will result in an IllegalStateException.

To avoid this, you could for example set player to null when you release it:

player.release();
player = null;

Or you could use a boolean flag to keep track of its state:

boolean isReleased;

// ...

player.release();
isReleased = true;

So you could check for this flag when necessary:

if (player != null && !isReleased) {
    if(player.isPlaying()) {
        // ...
    }
}

(don't forget to set it to false when appropriate)

like image 57
earthw0rmjim Avatar answered Nov 02 '22 05:11

earthw0rmjim


Adding to earthW0rmjim: I was facing the same issue (some audios didn't reproduce because of an ilegal state exception). What I found is that I was reseting my audio object on a callback. So, I was setting player.setDataSource(url) before I reset my object, because the callback was doing it after. My solution: player.reset() on the try / catch block of setDataSource and prepareAsync.

try {
        player.reset(); //Important line
        player.setDataSource(url);
        player.prepareAsync();

    } catch (Exception e) {
        Log.e(Constants.AUDIO_LOG_TAG, "Error playing file " + url, e);
    }

And look at the callback:

public void finishedPlayback(){
    player.reset(); //Executing after the try / catch (sometimes)
}
like image 2
Sebastian Paduano Avatar answered Nov 02 '22 05:11

Sebastian Paduano