I've asked a similar question but soon found it out of the topic, so let me explain my problem.
I have 5 audios. The goal is for each audio, play it 3 times.
Here is the code:
$('audio').each(function(index){
playAudio(this.player, index);
});
function playAudio(audio, index){
var loop = 3;
// This will loop 3 times
for(var i = 0; i < loop; i++){
audio.play();
$('.worship-items audio').eq(index).on('ended', function(){
// When the song has ended, set the progress(current time) back to 0 seconds.
audio.setCurrentTime(-1);
audio.pause();
});
}
}
The problem I'm having is that Console is giving me this error:
(15) Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().
Can someone help me out on this?
Edit: I was asked to add the html, so here it is:
<audio src="audio1.mp3"></audio>
<audio src="audio2.mp3"></audio>
<audio src="audio3.mp3"></audio>
<audio src="audio4.mp3"></audio>
<audio src="audio5.mp3"></audio>
The for
loop runs synchronously. You need to put the call to repeat in the ended
handler.
Similarly, .each()
runs synchronously. You need to start the next audio only when all the repeats of the previous one have concluded.
function playAudio(audios, index, loop, counter) {
if (counter >= loop) {
index++;
if (index >= audios.length) {
return;
}
playAudio(audios, index, loop, 0);
}
let audio = audios[index];
audio.player.play();
$(audio).off("ended").on("ended", function() {
this.player.setCurrentTime(-1);
playAudio(this, index, loop, counter + 1);
});
});
playAudio($(".worship-items audio"), 0, 3, 0);