Anderson Karu
Anderson Karu

Reputation: 667

Javascript or jQuery for getting the length of a video file before playing the video

Are there any useful Javascript or JQuery plugins for getting the length of a video (e.g. mp4, flv - I am open to any video format as long as I can get the video length) before playing the video file?

UPDATE 1:

<video controls>
 <source src="video.mp4" onerror="fallback(this.parentNode)">
 video not supported
</video>

<script>
document.write("The duration is: " + video[0].duration);
</script>

Upvotes: 4

Views: 6848

Answers (3)

Kai
Kai

Reputation: 2987

If you are using HTML5 video element , you can get by the use of "duration" property which will return in sec.

https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-media-duration

Otherwise, you may need to get the required information from server side.

Upvotes: 2

Ryan Gibbons
Ryan Gibbons

Reputation: 3601

To extend on Kai's answer, the duration property will only work with HTML5 video elements. You should look at http://mediaelementjs.com/ to help provide a shim to the api calls in older browsers.

Looks like They've implemented the duration() method https://github.com/johndyer/mediaelement/wiki/Events-and-Methods

Upvotes: 1

Christopher
Christopher

Reputation: 774

You can make a HEAD request for the target file and get file size. Without additional information about the file's particulars - that is, how it was encoded - you won't be able to calculate a duration with much certainty.

An example of such a request, using jQuery, can be found in the accepted answer to this similar question.

Note that you'll only have much luck doing this in the browser if the requests are being sent to the domain from which the javascript is served. If you're looking to make cross-domain requests, you will likely be better-served with something a bit more server-side.

Upvotes: 1

Related Questions