26
public static MediaPlayer mp=null;
public static void playGeneric(int name, final ImageButton button,final ImageButton pervious,Context context) {
    button.setEnabled(false);
button.setClickable(false);
pervious.setEnabled(false);
pervious.setClickable(false);
    try{
        if(mp != null && mp.isPlaying())
        {
            mp.stop();
            mp.release();
            mp = null;
           mp=MediaPlayer.create(context, name);
           mp.start();
        }
        else
        {
            mp = MediaPlayer.create(context, name);
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer arg0) {
                    //mp.prepare();
                    mp.start();

                }

            });
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
                System.out.println("Object released");
                button.setEnabled(true);
                button.setClickable(true);
                pervious.setEnabled(true);
                pervious.setClickable(true);
            }
        });
        }

    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        e.getMessage();
    } catch (NullPointerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        e.getMessage();
    }

}

give me java.lang.IllegalStateException on mp.isplaying() method.

I want to stop music if it's playing and play another song one after another.

logcat:

10-14 15:12:05.474: E/MediaPlayer(15411): prepareAsync called in state 8
10-14 15:12:05.474: W/System.err(15411): java.lang.IllegalStateException
10-14 15:12:05.474: W/System.err(15411):    at android.media.MediaPlayer.prepare(Native Method)
10-14 15:12:05.474: W/System.err(15411):    at com.rogerscenter.LearnReadWriteSpell.Utility.Music.playGeneric(Music.java:93)
10-14 15:12:05.474: W/System.err(15411):    at com.rogerscenter.LearnReadWriteSpell.LetterCategory.Letter_Lesson1_activity.onCreate(Letter_Lesson1_activity.java:140)
10-14 15:12:05.474: W/System.err(15411):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-14 15:12:05.474: W/System.err(15411):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1586)
10-14 15:12:05.474: W/System.err(15411):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
10-14 15:12:05.474: W/System.err(15411):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-14 15:12:05.474: W/System.err(15411):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
10-14 15:12:05.484: W/System.err(15411):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-14 15:12:05.484: W/System.err(15411):    at android.os.Looper.loop(Looper.java:123)
10-14 15:12:05.484: W/System.err(15411):    at android.app.ActivityThread.main(ActivityThread.java:3647)
10-14 15:12:05.484: W/System.err(15411):    at java.lang.reflect.Method.invokeNative(Native Method)
10-14 15:12:05.484: W/System.err(15411):    at java.lang.reflect.Method.invoke(Method.java:507)
10-14 15:12:05.484: W/System.err(15411):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-14 15:12:05.484: W/System.err(15411):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-14 15:12:05.484: W/System.err(15411):    at dalvik.system.NativeStart.main(Native Method)
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sydroid
  • 509
  • 1
  • 8
  • 16
  • 1
    please post full stack trace – Maxim Shoustin Oct 14 '13 at 09:27
  • did u fix it??? – Jeeva Jul 09 '18 at 13:29
  • 1
    This is mostly happening when you call release() multiple time. You should only call release when you no longer need the mediaplayer, and it is good practise to set it's value to null after that. This way your simple null checks will work. My approach is calling reset when possible, and only release when the whole page is closed – keybee Jan 23 '21 at 14:30

5 Answers5

25

Try changing mp.release() into reset(). that could help you.

Stephane Delcroix
  • 16,134
  • 5
  • 57
  • 85
Mester Hassan
  • 538
  • 5
  • 10
17

As android docs suggest that if mp is if has not been initialized at that time java.lang.IllegalStateException will be thrown so you have to initilize first or you have to write

check out the docs http://developer.android.com/reference/android/media/MediaPlayer.html#isPlaying()

try like this

 mp=MediaPlayer.create(context, name);

     try {

    if (mp.isPlaying()) {
        mp.stop();
        mp.release();
        mp=MediaPlayer.create(context, name);
    }



    mp.start();
} catch (Exception e) {
}
Siddhpura Amit
  • 14,534
  • 16
  • 91
  • 150
1

This could happen if you are trying to stop audio when the player hasn't started playing yet. Hence the IllegalStateException

See if you can prevent that. You can also putting a try catch around the isPlaying()

fun isPlaying(): Boolean {
    return try {
        mediaPlayer?.isPlaying == true
    } catch (illegalStateException: IllegalStateException) {
        DebugLog.d(TAG, illegalStateException.message)
        DebugLog.d(TAG, illegalStateException.stackTraceToString())
        false
    }
}
Abhinav Upadhyay
  • 140
  • 1
  • 14
0

Ok i am here with my solution, hope it will help others.

(i) if you are using videoView and mediaPlayer.isPlaying() (isNative) error occurs on activity stop

Add this onStop() method:

    if (videoView != null && videoView.isPlaying()) {
        videoView.pause();
        videoView.stopPlayback();
    }

Note: Don't use mediaPlayer.stop() or mediaPlayer.release() here when you work with videoView, it will throw IllegalException

(ii) If you are using mediaPlayer to play only audio

Add this onStop() method:

   try {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

Note: This is only for those who get error when your activity is in stop or in resume state.

hardkgosai
  • 309
  • 3
  • 5
-5

use runOnUiThread for mediaRecorder prepare.

private boolean prepareMediaRecorder() {

    mediaRecorder = new MediaRecorder();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            mediaRecorder.reset();
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);

            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            mediaRecorder.setOutputFile(filePath);

            try {
                mediaRecorder.prepare();
            } catch (IOException e) {
                mediaRecorder = null;
                return;
            }
            mediaRecorder.start();
            recording = true;
        }
    });

    return true;
}
Sagar Jethva
  • 986
  • 12
  • 26
  • Downvoting because: (1) The question is about MediaPlayer, not MediaRecorder, (2) it is pretty clear from the context of the code in the question that it is running on the UI thread, otherwise the other code (e.g. control enabling and disabling) that depends on being on the UI thread would be failing, and (3) there is no requirement that either MediaPlayer or MediaRecorder are used from the UI thread (they must be *created* on a thread with a Looper, and then events will be dispatched via that Looper, but once created can be used from other threads). – Jules Jan 06 '18 at 12:42