I have an array of mp4 videos that I need to display randomly with no repeats in a website header. After the last video plays, it should reshuffle and start over. The sequence needs to begin on page load. Each video needs to have an on hover text description specific to that video.
I am trying to use this shuffle code with this example of a no-repeat playlist
I haven't even gotten to the on-hover text because I can't get the shuffle sequence to work. I am not an expert.
This is the current version of my attempt. I know things are in the wrong order because I get "undefined" errors.
function shuffle(vids) {
let currentIndex = vids.length, randomIndex;
while (currentIndex != 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[vids[currentIndex], vids[randomIndex]] = [vids[randomIndex], vids[currentIndex]];
}
return vids;
playvids();
}
function playvids() {
var vids = ["vid1.mp4","vid2.mp4","vid3.mp4"];
for(var i = 0; i < vids.length; ++i){
document.getElementById("myvideo").addEventListener('ended', getnextfile);
document.getElementById("myvideo").src = "" + vids[i] + "";
}
}
function getnextfile() {
if(i >= vids.length){
shuffle(vids);
}
return vids[i++];
}
}
window.onload = playvids();
<video id="myvideo" src="" muted autoplay></video>
The window.onload is supposed to play a video from the array, then the eventlistener should call getnextfile at the end of the video, which is supposed to check to see if it is the last video in the array - if it is, reshuffle, if it isn't, increment by 1 to play the next video in the array. And I would prefer it shuffle the array before it plays for the first time, but I couldn't figure out how to do that.
My results ranged from undefined vars, to the video playing once and nothing happening, to the videos playing randomly but often repeating the same video more than once.