当mp4是唯一的源时,自定义HTML5video控件无法正常工作
问题:我只有一个video源(mp4),因为我正在尝试为tumblrvideo添加自定义控件。
如果只有mp4作为源video.duration
返回为NaN
。
作为使用3个源(mp4 / webm / ogg)的测试然后它可以工作,所以只能从wemb或ogg返回video.duration。
JSFIDDLE 1只有一个mp4作为源(所以不工作)。
JSFIDDLE 2有3个源文件正在工作。
HTML
0 0
JS:
// Video var video = document.getElementById("video"); // Buttons var playButton = document.getElementById("play-pause"); var muteButton = document.getElementById("mute"); var fullScreenButton = document.getElementById("full-screen"); // Sliders var seekBar = document.getElementById("seek-bar"); var volumeBar = document.getElementById("volume-bar"); // Event listener for the play/pause button playButton.addEventListener("click", function() { if (video.paused == true) { // Play the video video.play(); // Update the button text to 'Pause' playButton.innerHTML = "Pause"; } else { // Pause the video video.pause(); // Update the button text to 'Play' playButton.innerHTML = "Play"; } }); ... // Update the seek bar as the video plays video.addEventListener("timeupdate", function() { // Calculate the slider value var value = (100 / video.duration) * video.currentTime; // Update the slider value seekBar.value = value; }); ...
JS主要来自这里: http : //blog.teamtreehouse.com/building-custom-controls-for-html5-videos
我试过的:
video.addEventListener('loadedmetadata',function(){ console.log(video.duration); //returns NaN });
一些jQuery
$(document).ready(function(){ $("#video").on("timeupdate", function(event){ onTrackedVideoFrame(this.currentTime, this.duration); }); }); function onTrackedVideoFrame(currentTime, duration){ $("#current").text(currentTime); $("#duration").text(duration); }
另一种尝试:
window.setInterval(function(t){ if (video.readyState > 0) { var duration = $('#duration').get(0); var vid_duration = Math.round(video.duration); duration.firstChild.nodeValue = vid_duration; clearInterval(t); } },500);
也
这些解决方案似乎都没有奏效。
我也在SO上看过这个问题 。 其中有一个未经测试的投票答案。
要获得video的持续时间,您必须等待video源的元数据部分加载(这可能会根据video的编码方式而有很大差异 – 理想情况下,将MOOVprimefaces重新定位到开头的2遍编码已被使用,以便可以快速提取)。
通过侦听video对象上的loadedmetadata
事件,您的代码将知道何时可以安全地查询该事件。
在下面的代码中,您将看到我使用内联javascript(或可能在document.onload
)注册事件处理程序,而后者又调用该函数以在值可用时提取持续时间。 然后应该运行任何需要知道该值的代码。
我还为个人偏好添加了preload="auto"
,因为它有助于预缓存某些浏览器/设备中的内容,这在大多数情况下都不需要。