2012-02-16 60 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);