MediaPlayer force close after consecutive clicks
I've made a button and when you click it, it gives away a short sound(Max one second-sound). But after I've clicked the button about 20 times in a row I get force close.. The code is:
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickLis开发者_如何学JAVAtener() {
public void onClick(View v) {
// Perform action on clicks
MediaPlayer mp = MediaPlayer.create(getBaseContext(), R.raw.buzzer);
mp.start();
}
});
I've tried with mp.stop();
but then my sound stops after it have been played half of the time...
One more thing, does anyone know how to "prepare" the sound when I click? Because the sound gets delayed with some milliseconds the first time I press the button.
Create a MediaPlayer
member variable and initialize it in onCreate()
the same way you are doing in the listener. Then in the listener just use this code:
if(mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.start();
Then call mPlayer.release()
in your finish()
Activity. My guess is that since none of your MediaPlayer instances are being released, it's running out of memory to use.
The official document for MediaPlayer is actually incredibly descriptive and helpful: http://developer.android.com/reference/android/media/MediaPlayer.html
精彩评论