Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
185
rated 0 times [  189] [ 4]  / answers: 1 / hits: 16286  / 9 Years ago, wed, may 6, 2015, 12:00:00

I am trying to upload a video to server, and on client end. I am reading it using FileReader's readAsBinaryString().



Now, my problem is, I don't know how to read duration of this video file.



If i try reading the file, and assigning the reader's data to a video tag's source, then none of the events associated to the video tag are fired. I need to find the duration of file uploaded on client end.



Can somebody please suggest me something?


More From » html5-video

 Answers
58

You can do something like this for that to work:



  • read the file as ArrayBuffer (this can be posted directly to server as a binary stream later)

  • wrap it in a Blob object

  • create an object URL for the blob

  • and finally set the url as the video source.


When the video object triggers the loadedmetadata event you should be able to read the duration.


You could use data-uri too, but notice that browsers may apply size limits (as well as other disadvantages) for them which is essential when it comes to video files, and there is a significant encoding/decoding overhead due to the Base-64 process.


Example


Select a video file you know the browser can handle (in production you should of course filter accepted file types based on video.canPlayType()).


The duration will show after the above steps has performed (no error handling included in the example, adjust as needed).




var fileEl = document.querySelector(input);
fileEl.onchange = function(e) {

var file = e.target.files[0], // selected file
mime = file.type, // store mime for later
rd = new FileReader(); // create a FileReader

rd.onload = function(e) { // when file has read:

var blob = new Blob([e.target.result], {type: mime}), // create a blob of buffer
url = (URL || webkitURL).createObjectURL(blob), // create o-URL of blob
video = document.createElement(video); // create video element

video.preload = metadata; // preload setting
video.addEventListener(loadedmetadata, function() { // when enough data loads
document.querySelector(div)
.innerHTML = Duration: + video.duration + s; // show duration
(URL || webkitURL).revokeObjectURL(url); // clean up

// ... continue from here ...

});
video.src = url; // start video load
};
rd.readAsArrayBuffer(file); // read file object
};

<input type=file><br><div></div>




[#66722] Monday, May 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;