2012-02-16 59 views
1

我在使用'progress'事件检查视频是否加载100%时遇到了一些困难。它似乎只能在Chrome/Safari中使用。除非我尝试播放视频,否则Firefox似乎不想“预先加载”视频。html5视频 - 在动态加载的视频中使用进度事件

这里是我的html:

<div id="control"> 
    <a data-video="video/transport/1.0.webm">video1</a> 
    <a data-video="video/transport/2.0.webm">video2</a> 
    <a data-video="video/transport/3.0.webm">video3</a> 
    <a data-video="video/transport/4.0.webm">video3</a> 
    <a data-video="video/transport/5.0.webm">video3</a> 
</div> 

<video id="video" width="960" height="500" type="video/webm" autobuffer></video> 

这里是我的JS(代码chrome html5 video buffered.end event借来的):

$(function(){ 

    var vid = document.getElementById('video'); 

    vid.addEventListener('progress', onProgress, false); 

    $('#control a').click(function(){ 
     vid.src = $(this).attr('data-video'); 
     vid.load(); 
    }); 

}); 

function onProgress(e){ 

    var vid = document.getElementById('video'); 
    var percent = null; 

    if (vid.buffered.length > 0 && vid.buffered.end && vid.duration) { 
     percent = vid.buffered.end(0)/vid.duration; 
    } else if (vid.bytesTotal != undefined && vid.bytesTotal > 0 && vid.bufferedBytes != undefined) { 
     percent = vid.bufferedBytes/vid.bytesTotal; 
    } 

    if (percent !== null) { 
     percent = 100 * Math.min(1, Math.max(0, percent)); 

     console.log(percent); 
    } 

} 
+0

自动缓冲不是视频元素的属性,请尝试预加载,而不是设置为自动,无或元。 – 2012-02-16 16:21:10

+0

感谢您的提示 - @longlong让您的评论无处不在,我会接受它。你链接的讨论帮助我解决了我的问题。 – boz 2012-02-17 11:11:19

回答

3

检查这个讨论:HTML5 Video - File Loading Complete Event?

var videoDuration = $html5Video.attr('duration'); 

var updateProgressBar = function(){ 
if ($html5Video.attr('readyState')) { 
    var buffered = $html5Video.attr("buffered").end(0); 
    var percent = 100 * buffered/videoDuration; 

    //Your code here 

    //If finished buffering buffering quit calling it 
    if (buffered >= videoDuration) { 
      clearInterval(this.watchBuffer); 
    } 
} 
}; 
var watchBuffer = setInterval(updateProgressBar, 500);