在“已结束”的阵列中播放下一个视频

时间:2012-05-19 19:50:26

标签: javascript jquery arrays ipad html5

我有一系列视频,当一个结束时,阵列中的下一个应播放 我找到了这个脚本:

function myNewSrc() {
    var myVideo = document.getElementsByTagName("video")[0];
    myVideo.src =
        "http://cheerioscoupons.info/wp-content/uploads/_Cheerios-Coupons-1-300x283.jpg";
    myVideo.load();
    myVideo.play();
}
function myAddListener(){
    var myVideo = document.getElementsByTagName("video")[0];
    myVideo.addEventListener('ended',myNewSrc,false);
}

但我在当前脚本中实现它时遇到了麻烦,即

var numb = $(this).index(),
    videos = [
        "images/talking1.m4v",
        "images/talking2.m4v",
        "images/talking1.m4v",
        "images/talking2.m4v",
        "images/talking1.m4v",
        "images/talking2.m4v"
    ],
    myVideo = document.getElementById("myVid");
    myVideo.src = videos[numb];
    myVideo.load();
    setTimeout(function(){
        myVideo.play();
    }, 200);

所以,有两个问题:

  1. 他们在干涉吗?第一个根本不会改变视频。
  2. 如何将这些组合起来,以便下一个被调用的视频是数组中的下一个?

3 个答案:

答案 0 :(得分:5)

<强> 1
 document.getElementsByTagName将返回一个元素数组,而不是一个元素。所以

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

var myVideo = document.getElementsByTagName("video");
myVideo.load();   //wrong
myVideo.play();   //wrong

应该是什么:

myVideo[0].load()   //if there is only one

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

<强> 2
ended之后播放另一个视频,

var videos = [
    "images/talking1.m4v",
    "images/talking2.m4v",
];
function playArray(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);

直播演示: http://jsfiddle.net/DerekL/qeLcD/(替换为带有文字而不是视频的数组)

答案 1 :(得分:1)

我使用多个文件输入修改了视频输入,以便用户可以选择文件。

https://jsfiddle.net/geqd31pu/

<input id="file" type="file" multiple>    
<button onclick="play()">play</button>    
<video id="video" src="" autoplay controls></video>    
<script>
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)
</script>

答案 2 :(得分:-1)

播放让索引= 0视频= document.getElementsByTagName('video')[0]播放=()=> {const文件= document.getElementById('file')。files const file = files [index ++%files。长度] const url = window.URL.createObjectURL(file)video.src = url video.load()} video.addEventListener('ended',play,false)