问题
Similar questions to this one are asked a lot, and I have looked at other answers. What they say is that in order to play a sound (in this case "tock.wav", which is located in the assets folder) whenever a button is clicked, you should do the following:
public void onClick(View button) {
playButtonClickSound();
}
private void playButtonClickSound() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
}
try {
AssetFileDescriptor afd;
afd = getAssets().openFd("tock.wav");
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And this makes sense right? It seems like a good approach. The thing is that this works, except when the user presses the button(s) very quickly after each other. Then at some point, the sound just stops playing. If you wait a couple of minutes and try again, it plays again. Of course this is not what I want. The button click sound should always works, not just if the user isn't clicking too fast.
So does anyone have an idea as to what's causing this?
回答1:
try to use this
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
来源:https://stackoverflow.com/questions/20581844/button-click-sound-mediaplayer-crashes-if-buttons-are-pressed-too-rapidly