Button Click Sound MediaPlayer Crashes If Buttons Are Pressed Too Rapidly

谁说我不能喝 提交于 2019-12-11 06:39:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!