简体   繁体   English

onClick等待声音结束后再播放下一次单击

[英]onClick wait for sound to finish before playing the next click

I am working on a small project and I need a sound to be played when a user presses a button. 我正在做一个小项目,需要在用户按下按钮时播放声音。 That part I seem to have gotten down. 我似乎已经把那部分弄下来了。 But the problem is that if the user spams the button the sound will play over and over, overlapping itself. 但是问题是,如果用户向按钮发送垃圾邮件,声音将一遍又一遍地播放,并重叠在一起。 How do I lock out the button during the duration of the sound playing, or maybe put each click into a queue to play on after the other, and not at the instant of press? 如何在播放声音的过程中锁定按钮,或者如何将每次单击放入队列以在另一个之后而不是在按下按键时立即播放? This is what I have so far. 到目前为止,这就是我所拥有的。 I'm a bit of a noob to android development. 我对android开发有点菜鸟。 Thanks. 谢谢。

public void SOS(View v) {
    MediaPlayer mp = MediaPlayer.create(this, R.raw.sos);
    mp.start();
    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

    @Override
    public void onCompletion(MediaPlayer mp) {
        mp.stop();
    }
    });
}

Is it a jbutton? 是jbutton吗? If so then just use. 如果是这样,那就使用。 Replace with the name of your JButton. 替换为您的JButton的名称。

//Disables it.
<JbuttonName>.setEnabled(false);

//Enables it
<JbuttonName>.setEnabled(true);

Keep a reference to your mediaplayer instead of creating it each time, then play it only if it isn't already playing, like this: 保留对媒体播放器的引用,而不是每次都创建一个引用,然后仅在尚未播放时播放它,如下所示:

if(!mp.isPlaying())
{
     mp.start();
}

Try this, it worked for me: 试试这个,对我有用:

MediaPlayer mp;

public void mpStart() {
    mp = MediaPlayer.create(MainActivity.this, R.raw.sos);
    mp.start(); 
}

mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
                mp = null;
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM