How To Play A Sound File After Another Sound In Javascript
How do I play a sound file after another sound ends? If I do it like first.play(); second.play(); Both the sounds play at the same time. I want to play first.play() and when it en
Solution 1:
first.addEventListener('ended', function(){
second.play();
});
first.play();
Solution 2:
I would recommend kind of something:
// if using jQuery:var audios = $('audio');
audios.each(function(idx){
$(this).bind('ended', function(){
var next = audios.get(idx+1);
if(next){
next.get(0).play();
}
});
});
Solution 3:
You can also use a promise with a timeout:
const playPromise = first.play()
playPromise.then(() => {
setTimeout(() => {second.play()}, first.duration * 1000)
})
Solution 4:
I used the AudioScheduledSourceNode.onended.
I used four sounds, and put this code in a function:
sound1.play();
sound1.onended = function () {
sound2.play();
};
sound2.onended = function () {
sound3.play();
};
sound3.onended = function () {
sound4.play();
}
Here is the app live: insultinator-toy.netlify.app
Click the question mark button.
And the link to the ugly source code. jsahlsa
Post a Comment for "How To Play A Sound File After Another Sound In Javascript"