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();
}
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)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With