2
votes
var audioPlaying = false;

if (!audioPlaying) {
    // get a random audio element that has the class .sound
    audio = $('.s' + (Math.round(Math.random() * $('.sounds').size())));
    audio.get(0).play();
    audioPlaying = true;
    setTimeout(function(audioPlaying) {
        audioPlaying = false;
    }, 1000);
}

I'm working on a javascript thing that plays a sound on an event. I need to not play more than one sound every second. I have a function checks if audio is playing (via a true/false variable), then, if so, selects a random audio element and plays it. It then sets the variable to say audio is playing (true), then sets a timeout to switch the variable back to false after 1 second.

This should make it so that audio is played after at a minimum of 1 second. However, it doesn't seem to ever set the audioPlaying variable back to false. One of the sounds is played and none after that. If I remove the code that changes audioPlaying to true, the sounds are played without any spacing between them.

Anyone know what's wrong?

1

1 Answers

0
votes

Try something like this:

var audioPlaying = {
    _audioPlayingNow: false,

    playAudio: function()
    {
        if ( !audioPlaying._audioPlayingNow )
        {
            var audio = $('.s' + (Math.round(Math.random() * $('.sounds').size())));
            audio.get(0).play();

            audioPlaying._audioPlayingNow = true;
            setTimeout( audioPlaying._resetAudioPlaying, 1000 );
        }
        else
        {
            setTimeout( audioPlaying.playAudio, 1000 );
        }
    },

    _resetAudioPlaying: function()
    {
        audioPlaying._audioPlayingNow = false;
    }
}