当前视频文件不可用时如何跳转到下一个视频?

时间:2014-01-16 11:08:58

标签: javascript html5-video

我正在尝试逐个播放存储在文件夹中的视频文件列表,但如果任何文件丢失或删除,程序将停止,但我希望它跳转到下一个视频并继续执行有没有办法捕获此错误并跳转到下一个错误?

function advanceVideo()
{          
  video_count++;
  if (video_count > num_files) video_count = 1; 
  videoPlayer.setAttribute("src","video/video"+video_count+".ogg");  
  video.load();
  video.play();     
}  

我正在使用上述功能访问文件夹中的视频文件。

2 个答案:

答案 0 :(得分:0)

尝试使用try-catch阻止:

function advanceVideo()
{          
  video_count++;
  if (video_count > num_files) video_count = 1;       
  videoPlayer.setAttribute("src","video/video"+video_count+".ogg");  
  try {        
    video.load();
    video.play();      
  } catch (e) { }
} 

答案 1 :(得分:0)

利用<video />元素提供的各种事件

// function to load the next video (without .play())
function advanceVideo() {
    video_count = (video_count + 1) % num_files;

    this.setAttribute("src", "video/video" + video_count + ".ogg");
    this.load();
}

// if the current video has reached the end, load the next
videoPlayer.addEventListener("ended", advanceVideo);

// if the browser fetched enough data to play the video start playing
videoPlayer.addEventListener("canplay", function() {
    this.play();
});

// if an error occured load the next video
videoPlayer.addEventListener("error", advanceVideo);

<强>更新
这应该按照您在评论中提出的要求进行操作

var num_files = 2,
    playedVideos = 0;

// load next video
function advanceVideo() {
    // current video id or -1 if not found
    var curId = parseInt((/video(\d+)\.ogg$/.exec(this.src) || [, -1])[1], 10);

    // reset if all videos have been played
    if (playedVideos == num_files) {
        playedVideos = 0;
        curId = -1;
    }

    this.src = "video/video" + (curId + 1) + ".ogg";
    this.load();
}

// if the current video has reached the end, load the next
videoPlayer.addEventListener("ended", function() {
    playedVideos++;
    advanceVideo();
});

// if the browser fetched enough data to play the video start playing
videoPlayer.addEventListener("canplay", function() {
    this.play();
});

// if an error occured load the next video
videoPlayer.addEventListener("error", advanceVideo);

如果播放的视频数量少于num_files所示,则会以“无限循环”结束,因为它会尝试所有视频,直到curId达到Infinity的值!