我喜欢在上传之前从用户桌面上的本地文件中找到视频长度。 “ video.onload”事件没有触发(请参见代码),因此在视频加载后,我通过setTimeout帮助自己。但是我不喜欢使用setTimeout。有没有更清洁的方法?
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
var output = [];
for (var i = 0, f; f = files[i]; i++) {
var video = document.getElementById('myVideo');
var obj_url = window.URL.createObjectURL(f);
video.src = obj_url;
console.log(f.name+ " " +f.type);
console.log(video.src);
video.onload = function() {
// It didn't work so I used delayedchk()
// window.URL.revokeObjectURL(this.src);
}
delayedchk();
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
function show(){
vid = document.getElementById("myVideo");
document.getElementById("laenge").innerHTML = Math.floor(vid.duration);
vid.play();
window.URL.revokeObjectURL(vid.src);
}
function delayedchk(){
var vdur = document.getElementById("myVideo").duration;
console.log(typeof vdur +' = '+vdur);
if( isNaN(vdur) ){
setTimeout(delayedchk,500);
}else{
show();
}
}
<!DOCTYPE html>
<html>
<body onload="show()">
<video id="myVideo" src="https://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4"></video>
<h1>Lenght: <span id="laenge"></span> sec.</h1>
<input type="file" id="files" name="files[]" multiple />
</body>
</html>
答案 0 :(得分:0)
您可以通过收听duration
property事件来检索视频的loadedmetadata
:
var myVideoPlayer = document.getElementById('myVideo');
myVideoPlayer.addEventListener('loadedmetadata', function() {
document.getElementById('laenge').innerHTML = myVideoPlayer.duration;
});
<h1>Length: <span id="laenge"></span> sec.</h1>
<video id="myVideo" src="https://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4" autoplay></video>