Skip to content

Instantly share code, notes, and snippets.

@joshbeckman
Created September 10, 2014 19:16
Show Gist options
  • Save joshbeckman/7e42c24f8f7bfd5b8ef6 to your computer and use it in GitHub Desktop.
Save joshbeckman/7e42c24f8f7bfd5b8ef6 to your computer and use it in GitHub Desktop.
Find duration of media file asynchronously in JavaScript
function getDuration(fileURL, cb){
var a = document.createElement('audio');
a.src = fileURL;
a.preload = 'metadata';
document.body.appendChild(a);
a.addEventListener('loadedmetadata', function(evt){
var d = evt.target.duration;
cb(d);
}, false);
}
// Notes:
// Does not require full file to load, and can be retrieved async.
// Example:
// getDuration('http://media.tts-api.com/c99414d17e9831923df12bda67c3b468da7b9619.mp3', function(d){alert(d);}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment