Alan
Alan

Reputation: 1265

Javascript, play sounds within a loop

I need to play a series of sounds in sequence. With my current code the sounds pretty much play all at once instead of in order. I've tried various setTimeout(), setInterval() combos, but since the sounds are of various lengths I haven't been able to make this work. Is there a way I could set a conditional flag to insure that sounds don't overlap? Is a sleep() function the only answer?

function playAll()
{

for (i = 0; i < 10; i++) {
playSound(sound[i]);

// if sound is finished, continue loop
// need some type of flag?


}

}

Upvotes: 0

Views: 171

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370949

HTMLAudioElements fire a ended event when the element stops playing. If you promisify playSound so that it returns a Promise when the next stop event fires on the element, you can just await the call inside the loop:

const playSound = soundElement => {
    soundElement.play();
    return new Promise((resolve) => {
        soundElement.addEventListener('ended', resolve)
    })
}
function playAll() {
    for (let i = 0; i < 10; i++) { // don't forget to declare the variable with `let`
        await playSound(sound[i]);
    }
}

Upvotes: 1

Related Questions