查找视频元素的缓冲百分比

时间:2016-05-13 05:11:30

标签: javascript html html5

我需要找到来自<video>元素的视频的缓冲百分比。

我试图使用以下代码找到它,

videoElement.addEventListener("progress", bufferHandler);
var bufferHandler = function(e) {
    var buffered = e.target.buffered.end(0);
    var duration = e.target.duration;
    var buffered_percentage = (buffered / duration) * 100;
    console.log(buffered_percentage);
}

但价值不正确,如果我播放完整视频buffered_percentage而不是100%。

var videoElement = document.getElementById("myVideo");
videoElement.addEventListener("progress", bufferHandler);
var bufferHandler = function(e) {
  var buffered = e.target.buffered.end(0);
  var duration = e.target.duration;
  var buffered_percentage = (buffered / duration) * 100;
  console.log(buffered_percentage);
}
<video id="myVideo" width="320" height="176" controls>
  <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
    <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
      Your browser does not support HTML5 video.
</video>

1 个答案:

答案 0 :(得分:5)

Media Eventprogress

  

定期发送以通知感兴趣的各方进度下载   媒体。有关当前媒体数量的信息   已下载的媒体元素已缓冲   属性。

OP发布的代码:

    <script>
var videoElement = document.getElementById("myVideo");
videoElement.addEventListener("progress", bufferHandler);
var bufferHandler = function(e) 
{
  var buffered = e.target.buffered.end(0);
  var duration = e.target.duration;
  var buffered_percentage = (buffered / duration) * 100;
  console.log(buffered_percentage);
}
    </script>

输出控制台:

enter image description here

如果可以,请按以下方式添加script,这样会很棒:

    <script>

var videoElement = document.getElementById("myVideo");
videoElement.addEventListener("progress", bufferHandler);
function bufferHandler(e)
 {
if (videoElement && videoElement.buffered && videoElement.buffered.length > 0 && videoElement.buffered.end && videoElement.duration)
 {

  var buffered = e.target.buffered.end(0);
  var duration = e.target.duration;
  var buffered_percentage = (buffered / duration) * 100;
  console.log(buffered_percentage);
  }
}


    </script>

输出控制台: 51.699%

enter image description here

视频缓冲100%:

enter image description here

经过测试:

enter image description here

注意:已使用另一个长度和大小的视频进行测试,而不是由OP发布。

由于

&#13;
&#13;
var videoElement = document.getElementById("myVideo");
videoElement.addEventListener("progress", bufferHandler);
function bufferHandler(e)
 {
if (videoElement && videoElement.buffered && videoElement.buffered.length > 0 && videoElement.buffered.end && videoElement.duration)
 {
  
  var buffered = e.target.buffered.end(0);
  var duration = e.target.duration;
  var buffered_percentage = (buffered / duration) * 100;
  console.log(buffered_percentage);
  }
}
&#13;
<video id="myVideo" controls="controls">
  <source src="http://client.99nfomatics.in/test/files/B.mp4" type="video/mp4">
  
</video>

 
&#13;
&#13;
&#13;