Javascript For循环遍历所有视频,但只播放最后一个HTML5视频。为什么?

时间:2015-06-20 18:29:02

标签: javascript html5 html5-video opera

我正在尝试在名为sources的数组中添加所有源视频路径。然后,我正在尝试使用我的HTML5视频播放器播放它们。但是,当我运行循环时,(使用警报消息进行调试) - 每次只播放最后一个视频,尽管它遍历所有视频名称。这是为什么?!

<script>
  var i=1;
  var sources = new Array(4);
  var oggVid = document.getElementById('oggSource');      
  var mp4Vid = document.getElementById('mp4Source');
  var webmVid = document.getElementById('webmSource');
  var player = document.getElementById('videoPlayer');
  for (i=1; i < sources.length; i++) {   
      sources[i]="/videolibrary/"+i+".webm";
      var srcName=sources[i];
          // alert(i + "   " + sources.length + " " + srcName);

      }
    function next() { 
      player.pause();
      for (i=1; i < sources.length; i++) {   
      webmVid.setAttribute('src', sources[i]);
      mp4Vid.setAttribute('src', sources[i]);
      oggVid.setAttribute('src', sources[i]);
      player.load();
      player.play(); 
      alert(i + "   " + sources.length + " " + sources[i]);
      }} </script>

警报消息的输出(当我单击“下一步”按钮(加载下一个函数)时)会快速连续显示所有源[i]值,并且播放器每次只播放最后一个值。我不明白为什么会这样!谢谢你的帮助。

2 个答案:

答案 0 :(得分:0)

每次点击下一步时,您都不想浏览所有视频。相反,您只想前进到下一个视频。试试这个:

var currentVideo = 1;

function next() { 
    player.pause();
    currentVideo++;
    if(currentVideo >= sources.length) currentVideo = 1;
    webmVid.setAttribute('src', sources[currentVideo]);
    mp4Vid.setAttribute('src', sources[currentVideo]);
    oggVid.setAttribute('src', sources[currentVideo]);
    player.load();
    player.play(); 
    alert(currentVideo + "   " + sources.length + " " + sources[currentVideo]);
}

答案 1 :(得分:0)

我得到了你想要做的事情。为此,你需要了解以下概念: - 1.Loop不会等你的代码播放所有的视频。它是异步的。通过你的代码进入player.play()函数的时间,计数器达到你最后一个视频的最后一个值。这就是为什么你是得到那个问题。

要解决这些问题,您需要了解CallBack和setTimeout概念。

var i=0;
function next() { 

    setTimeout (function()
    {
      i++;
      player.pause();

      webmVid.setAttribute('src', sources[i]);
      mp4Vid.setAttribute('src', sources[i]);
      oggVid.setAttribute('src', sources[i]);
      player.load();
      player.play(); 
      next();
      }
  },6000)
} 

这里代码正在做的是设置i = 1,播放视频暂停6秒,然后将计数器增加到2再次播放视频6秒,依此类推。 您可以设置要运行视频的时间。