Skip to content

Instantly share code, notes, and snippets.

@davorbadrov
Created March 28, 2014 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davorbadrov/9834790 to your computer and use it in GitHub Desktop.
Save davorbadrov/9834790 to your computer and use it in GitHub Desktop.
Check video duration from a video selected through the <input> element, it should be usable with drag'n'drop too. NOTE: this hasn't been tested
/* global document, URL, alert */
// TODO: Check support for video types & URL.createObjectURL() function
// NOTE: IE9 doesn't seem to support URL object, but a polyfill seems to exist: https://gist.github.com/arv/1384398
function getDuration(videoFile, callback) {
'use strict';
var type = videoFile.type;
var videoEl = document.createElement('video');
videoEl.preload = 'metadata';
var canPlay = videoEl.canPlayType(type);
canPlay = canPlay === '' ? 'no' : canPlay;
if (canPlay === 'no') {
alert('Your browser doesn\'t support the video format: ' + type);
}
if (!URL || !URL.createObjectURL) {
alert('Your browser can\'t read the video from input'); // if not supported, use apolyfill or handle on server? how? ...
}
var fileUrl = URL.createObjectURL(videoFile);
videoEl.src = fileUrl;
videoEl.addEventListener('loadedmetadata', function() {
callback(videoEl.duration);
});
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Video Duration Test</title>
</head>
<body>
<h1>Video Duration Test</h1>
<div class="results">
Video Duration:
</div>
<input id="video-input" type="file" accept="video/*">
<script src="checkDuration.js"></script>
<script>
var input = document.getElementById('video-input');
input.addEventListener('change', function(event) {
var file = event.target.files[0];
getDuration(file, function(duration) {
document.querySelector('.results').innerHTML = 'Video Duration: ' + duration + ' (in seconds)';
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment