javascript html5 视频 - 对动态加载的视频使用进度事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9313697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
html5 video - using the progress event with dynamically loaded videos
提问by boz
I'm having a bit of difficulty using the 'progress' event to check if a video is 100% loaded. It only seems to work in Chrome/Safari. Firefox doesn't seem to want to 'preload' a video unless I try to play it.
我在使用 'progress' 事件来检查视频是否 100% 加载时遇到了一些困难。它似乎只适用于 Chrome/Safari。除非我尝试播放,否则 Firefox 似乎不想“预加载”视频。
Here is my html:
这是我的 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>
Here is my js (code borrowed from chrome html5 video buffered.end event):
这是我的 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);
}
}
回答by longi
check this discussion: HTML5 Video - File Loading Complete Event?
检查此讨论:HTML5 视频 - 文件加载完成事件?
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);