Liam Schnell
Liam Schnell

Reputation: 482

Android MediaPlayer does not start again after being stopped

I want to play a sound. The first time it works well, but if I stop it and want to restart it nothing happens...Any idea?

final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.sex);
ImageButton andvib = (ImageButton)findViewById(R.id.vib_toggle);
final AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
andvib.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        am.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0);
        Vibrator vibr = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        vibr.cancel();
        if(vibrating==false) {
            if(style == 0)
                vibr.vibrate(durat, 0);
            if(style == 1){
                vibr.vibrate(staccato, 0);
            }
            if(style == 2){
                vibr.vibrate(wild, 0);
            }
            try {
                mp.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mp.start();
            mp.setLooping(true);
            vibrating = true;
        }
        else {
            vibrating = false;
            mp.stop();
            try {
                mp.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            vibr.cancel();
        }
    }
});

Upvotes: 5

Views: 6212

Answers (2)

FoamyGuy
FoamyGuy

Reputation: 46856

You may have to call mp.prepare() before you call start() the second time.

Upvotes: 0

Bruno Oliveira
Bruno Oliveira

Reputation: 5076

When using MediaPlayer, you should always refer to the state change diagram that you can see here:

http://developer.android.com/reference/android/media/MediaPlayer.html

As you can see from the diagram, after calling stop() on a MediaPlayer, it goes to the Stopped state and you need to call prepare() again to move it to the Prepared state before calling play().

Remember that preparation may take long, so doing that all the time may cause a poor user experience, especially if you are doing it from the main thread (the UI will freeze while the MediaPlayer is preparing). If you play the sound frequently, you should really only prepare() it once, and then always keep it in the Started, Paused or PlaybackCompleted states.

Bruno Oliveira, Developer Programs Engineer, Google

Upvotes: 7

Related Questions