I am trying to loop through a number of elements to change the audio source of a single audio element, play it, and once ended, change the new src and play it until the loop has gone through all elements:
var contentAudio = new Audio();; function audioLoop(index, audioModel) { while (index < audioModel.length) { var audio = contentAudio; audio.src = audioModel[index].src; audio.play() audio.addEventListener('ended', function () { index++; }); } console.log('done'); }
It seems that adding the event listener is not working. The audio does not play and I am stuck in an endless loop. The audio ended event is never triggered. Am I doing anything wrong? Is there a better alternative?
Answer
The while
loop is synchronous so it doesn’t wait for your ended
event. Here is what I’m suggesting:
var contentAudio = new Audio(); function audioLoop(index, audioModel) { (function process(done) { if (index >= audioModel.length) { done(); return; } var audio = contentAudio; audio.src = audioModel[index].src; audio.play() audio.addEventListener('ended', function () { index++; process(done); }); })(function () { console.log('done'); }); }
Also is audioModel
an array. If so I think you should be using audioModel[index].src
instead of audioModel.src
.