This is a super quick question. Here is a piece of code that plays an array of songs in order. Somehow, when the array finishes playing, it repeats the first song. Any idea why? I am going insane because I cant figure it out...
Code below in the link: https://jsfiddle.net/wt2joay4/
var song1 = $('#sound-1');
var song2 = $('#sound-2');
var song3 = $('#sound-3');
var audioArray = [song1, song2, song3];
var i=0;
var lastPlayedFile = null;
$(".click").click(function(){
if(lastPlayedFile !== null) {
lastPlayedFile[1].currentTime = 0;
lastPlayedFile.trigger('pause');
}
if (i< audioArray.length){
lastPlayedFile = audioArray[i];
audioArray[i].trigger('play');
i++;
} else if (i>=audioArray.length){
i = 0;
lastPlayedFile = audioArray[0];
audioArray[i].trigger('play');
};
});
Thanks!
The issue is with i=0. This should be i=1.
The i variable is used to indicate which song to play next rather than current index.
So in i<audioArray.length it plays audioArray[i] and then does i++.
But in i>=length it plays audioArray[0] but leaves i pointing at 0, so the next played is again 0.
The fix is to leave i=1 after re-looping. This could use the same concept as above: i=0; ...play [i]...; i++; or just i=1.
} else if (i>=audioArray.length){
lastPlayedFile = audioArray[0];
audioArray[i].trigger('play');
i = 1;
};
});
Suggestion: Use a better variable name than i. If this was named nextIndex then nextIndex=0 would be clear(er) that it's going to play 0 next (when it's already playing 0).
Alternative suggestion: Keep i as the current index and increase before starting the next, eg:
var song1 = $('#sound-1');
var song2 = $('#sound-2');
var song3 = $('#sound-3');
var audioArray = [song1, song2, song3];
var i = -1;
$(".click").click(function() {
if (i >= 0) {
audioArray[i].currentTime = 0;
audioArray[i].trigger('pause');
}
i++;
if (i >= audioArray.length)
i = 0;
audioArray[i].trigger('play');
});
(and change i to currentIndex, but left as i above to compare with original)