从Array加载HTML5视频播放器

时间:2014-09-23 18:00:13

标签: javascript arrays html5 video dynamic

我有一系列视频,我想将它们加载到当前页面上设置的视频播放器中。这就是我所拥有的:

var current = 0;

var videos = ["01", "02", "03", "04"];

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;

}

function shuffleAll(){
    shuffle(videos);
}

function loadVideo(){
    var video = document.getElementById('video');
    var mp4 = document.getElementById('mp4');
    d = new Date();

    mp4.src = "videos/" + videos[current] + '.mp4';
    alert(mp4.src);
    video.load();
    video.play();

}

我的HTML:

<body onLoad="shuffleAll()">

<a href="" onClick="javascript:loadVideo();">Load Video</a><br>
<video id="video" controls width="560">
     <source id="mp4" type="video/mp4" />
</video>
</body>

但是我点击了我的加载视频按钮,它没有做任何事情。我错过了什么?

1 个答案:

答案 0 :(得分:1)

您需要暂停视频,然后加载视频然后播放。这真是一个棘手的儿子。您需要将监听器添加到视频按钮(通过随机化或其他方式更改源)

videobutton.addEventListener("click", function(event) {
   video.pause();
   mp4.setAttribute('src', 'videos/' + videos[current] + '.mp4');
   video.load();
   video.play();
},false);

这样可行。

var current = 0;

var videos = ["01", "02", "03", "04"];

function shuffle(array) {
 var currentIndex = array.length, temporaryValue, randomIndex ;
 // While there remain elements to shuffle...
 while (0 !== currentIndex) {
 // Pick a remaining element...
 randomIndex = Math.floor(Math.random() * currentIndex);
 currentIndex -= 1;
 // And swap it with the current element.
 temporaryValue = array[currentIndex];
 array[currentIndex] = array[randomIndex];
 array[randomIndex] = temporaryValue;
}

 return array;

}

function shuffleAll(){
   shuffle(videos);
} 

function loadVideo(){
   var video = document.getElementById('video');
   var mp4 = document.getElementById('mp4');
   d = new Date();
   video.pause();
   mp4.setAttribute('src', 'videos/' + videos[current] + '.mp4');
   video.load();
   video.play();
 }