Muhammad Salman Muhammad Salman - 5 months ago 39
Android Question

Unable to play sound twice Android Mediaplayer application crashing

Unable to play sound twice causing Android Mediaplayer application to crash

mp = MediaPlayer.create(context, R.raw.audio1);
final ImageButton play = (ImageButton) findViewById(R.id.play_button_dua_seher);

play.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

try {
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(context, R.raw.audio1);
}
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});

final ImageButton stop = (ImageButton) findViewById(R.id.stop_button_dua_seher);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mp != null)
{
mp.stop();
mp.reset();
mp.release();
}
}
});


Logcat

06-15 14:34:59.470 11697-11697/com.toptech.android.ramadanduas

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.toptech.android.ramadanduas, PID: 11697
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.toptech.android.ramadanduas.duaseher$2.onClick(duaseher.java:53)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit

Answer

Seems like the problem is you call release() on your MediaPlayer instance when clicking the stop button, but you don't check it's state when (re)starting the playback.

This means you could call isPlaying() on a released MediaPlayer instance, which will lead to an IllegalStateException.

You should somehow keep track of the state of the MediaPlayer instance (with a boolean flag for example) or set it to null after the release so you could perform null value checks after.

You could do something like this:

// in your play button's onClick()
if (mp != null && mp.isPlaying()) { // check for null value also
    mp.stop();
    mp.reset();
} else {
    mp = MediaPlayer.create(context, R.raw.audio1);
}
mp.start();

and

// in your stop button's onClick()
mp.release();
mp = null; // set it to null