Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    }
});
like image 547
Liam Schnell Avatar asked Mar 29 '11 14:03

Liam Schnell


1 Answers

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

like image 91
Bruno Oliveira Avatar answered Nov 06 '22 23:11

Bruno Oliveira