Skip to content Skip to sidebar Skip to footer

Play Next Video In An Array On "ended"

I have an array of videos, and when one ends, the next in the array should play. I've found this script: function myNewSrc() { var myVideo = document.getElementsByTagName('vide

Solution 1:

1.document.getElementsByTagName will return an array of elements, not one. So

var myVideo = document.getElementsByTagName("video");
myVideo.addEventListener('ended',myNewSrc,false);    //wrongvar myVideo = document.getElementsByTagName("video");
myVideo.load();   //wrong
myVideo.play();   //wrong

What it should be is:

myVideo[0].load()   //if there is only onefor(var i=0;i<myVideo.length;i++){
    myVideo[i].load();    //if there is more
}

2. Play another video after ended,

var videos = [
    "images/talking1.m4v",
    "images/talking2.m4v",
];
functionplayArray(index,ele,array,listener){
    ele.removeEventListener(listener||0);
    ele.src = array[index];
    ele.load();
    ele.play();
    index++;
    if(index>=array.length){
        index=0;
    }
    listener = ele.addEventListener('ended',function(){
        playArray(index,ele,array,listener);
    },false);
}
playArray(0,document.getElementById("myVid"),videos);

LIVE DEMO:http://jsfiddle.net/DerekL/qeLcD/ (Replaced with an array with text instead of viedos)

Solution 2:

I modified the videos input using multiple file input so that the user can select the files.

https://jsfiddle.net/geqd31pu/

<inputid="file"type="file"multiple><buttononclick="play()">play</button><videoid="video"src=""autoplaycontrols></video><script>let index = 0
video = document.getElementsByTagName('video')[0]
play = () => {
  const files = document.getElementById('file').filesconst file = files[index++ % files.length]
  const url = window.URL.createObjectURL(file)
  video.src = url
  video.load()
}
video.addEventListener('ended', play, false)
</script>

Solution 3:

play let index = 0 video = document.getElementsByTagName('video')[0] play = () => { const files = document.getElementById('file').files const file = files[index++ % files.length] const url = window.URL.createObjectURL(file) video.src = url video.load() } video.addEventListener('ended', play, false)

Post a Comment for "Play Next Video In An Array On "ended""