开发者

Problem playing sound on Timer

开发者 https://www.devze.com 2023-02-16 20:39 出处:网络
I have started a Timer on a screen , for example 20 seconds. When the time remaining is 5 seconds , I am playing a beep sound .

I have started a Timer on a screen , for example 20 seconds.

When the time remaining is 5 seconds , I am playing a beep sound . The problem is that the sound is being played multiple times(3-4 times) , whereas I need a single beep . The duration of the audio file is 0.09 seconds.

Kindly find below the code

public void onTick(long millisUntilFinished) {

            long timeLeft = millisUntilFinished / 1000;

            if (timeLeft == 5) {
                   playAlertSound(R.raw.beep);

                }
    }

    private MediaPlayer mPlayer;

    public void pl开发者_如何学CayAlertSound(int sound) {

        MediaPlayer mp = MediaPlayer.create(getBaseContext(), sound);
        mp.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // TODO Auto-generated method stub
                mp.release();
            }

        });
        // and add the setLooping and setVolume calls here..
        mp.setLooping(false);
        mp.setVolume(1.0f, 1.0f);
        mp.start(); // to here..
}

Kindly provide your inputs/suggestions , where the problem is

Thanks in advance.

Warm Regards,

CB


What kind of timer are you using? (Probably a Handler is the better way to do it). It is hard to answer the question if you don't provide the details, but I'm guessing that the onTick method is called multiple times. The condition you are using will evaluate to true for a numerous values of the millisUntilFinished parameter. You should make sure that onTick is called only once per second for example. Another solution will be to add a flag variable of boolean type that will mark the audio being played once. You will change the condition to also test if this variable is false, before playing the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号