Skip to content

Instantly share code, notes, and snippets.

@yuraloginoff
Last active July 25, 2022 05:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuraloginoff/1e390ea33edb83d82732 to your computer and use it in GitHub Desktop.
Save yuraloginoff/1e390ea33edb83d82732 to your computer and use it in GitHub Desktop.
html5 audio queue
<!doctype html>
<html>
<head>
<script>
//This plays a file, and call a callback once it completed (if a callback is set)
function play(audio, callback) {
audio.play();
if (callback) {
//When the audio object completes it's playback, call the callback
//provided
audio.addEventListener('ended', callback);
}
}
//Changed the name to better reflect the functionality
function play_sound_queue(sounds) {
var index = 0;
function recursive_play() {
//If the index is the last of the table, play the sound
//without running a callback after
if (index + 1 === sounds.length) {
play(sounds[index], null);
} else {
//Else, play the sound, and when the playing is complete
//increment index by one and play the sound in the
//indexth position of the array
play(sounds[index], function() {
index++;
recursive_play();
});
}
}
//Call the recursive_play for the first time
recursive_play();
}
function play_all() {
play_sound_queue([new Audio("http://www.smldesign.com/1.wav"), new Audio("http://www.smldesign.com/2.wav"), new Audio("http://www.smldesign.com/3.wav")]);
}
</script>
</head>
<body>
<a href="javascript:;" onclick="play_all();">PLAY THIS!</a>
</body>
</html>
@yuraloginoff
Copy link
Author

No license or copyright needed. Free for commercial and personal usage.

Copy link

ghost commented Sep 30, 2021

Works great! It seems that there's a noticeable delay (1-2 seconds) before the next sound start's playing though. Do you know what could be causing this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment