After spending hours trying to solve this, I've hit a roadblock. I've searched through similar questions on stackoverflow, but none of the solutions seem to work for me.
I'm currently looping through an array of videos and need to insert each video into the audio element to quickly retrieve its duration and position in the playlist.
This is what I originally had:
// Set time in playlist for each video
for (let index=0; index<this.playlist.length; index++) {
var audio = document.getElementById('audio');
console.log('INDEX: ' + index);
self.playlist[index].timeInPlaylist = [];
self.playlist[index].duration = 0;
audio.setAttribute('src', self.playlist[index].bucketRef);
audio.addEventListener('canplaythrough', function(e){
videoDuration = Math.round(e.currentTarget.duration);
console.log("Duration of video number " + index + ": " +
videoDuration + " seconds");
self.playlist[index].duration = videoDuration;
self.playlist[index].timeInPlaylist[0] = playlistLength;
playlistLength = playlistLength + videoDuration;
self.playlist[index].timeInPlaylist[1] = playlistLength;
});
};
The code kept the index the same, causing the length of the last video in the array to be logged three times. After some investigation, I realized I needed to use closures due to adding event listeners inside the loop. So, I refactored it to the following version:
function log(e, index) {
videoDuration = Math.round(e.currentTarget.duration);
console.log("Duration of video number " + index + ": " + videoDuration + " seconds");
self.playlist[index].duration = videoDuration;
self.playlist[index].timeInPlaylist[0] = playlistLength;
playlistLength = playlistLength + videoDuration;
self.playlist[index].timeInPlaylist[1] = playlistLength;
}
// Set time in playlist for each video
for (let index=0; index<this.playlist.length; index++) {
var audio = document.getElementById('audio');
console.log('INDEX: ' + index);
self.playlist[index].timeInPlaylist = [];
self.playlist[index].duration = 0;
audio.setAttribute('src', self.playlist[index].bucketRef);
debugger;
(function() {
var i = index;
audio.addEventListener("canplaythrough", function(e) { log(e, i); });
})();
};
This update solved the issue with indexes, but I'm still only receiving the duration of the last video in the array.
Any feedback would be greatly appreciated. This problem has been a real challenge for me.