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();
}
}
});
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
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