如果单击按钮的速度过快,则单击按钮的声音MediaPlayer会崩溃 [英] Button Click Sound MediaPlayer Crashes If Buttons Are Pressed Too Rapidly

查看:101
本文介绍了如果单击按钮的速度过快,则单击按钮的声音MediaPlayer会崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多类似的问题被问到了,我已经看了其他答案.他们说的是,每当单击按钮时,为了播放声音(在本例中为"tock.wav",位于资产文件夹中),您应该执行以下操作:

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?

推荐答案

尝试使用此功能

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you

这篇关于如果单击按钮的速度过快,则单击按钮的声音MediaPlayer会崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆