简体   繁体   中英

Video Lenght by JavaScript before uploading video file

I like to find out the video lenght from a local file on users desktop before uploading. The "video.onload" event didn't fire (see code) so I helped myself with a setTimeout once the video is loaded. But I don't like to use the setTimeout. Is there a cleaner way?

 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> 

You can retrieve the video's duration property by listening to the loadedmetadata event:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM