Get the Duration of an Audio or Video File in Javascript

It is sort of straightforward to get the playback size (in seconds) of an audio or video file. The file could also be in no matter format that the browser helps – mp3, mp4, ogg, wav, and so forth.
When Using the HTML5 Elements
When utilizing the HTML5 <audio> or <video> parts, you may merely verify the length property in Javascript.
What’s the one factor each developer desires? More screens! Enhance your coding expertise with an exterior monitor to extend display screen actual property.
var audio_duration = doc.querySelector('audio').length; // 10.026666641235352
// or
var video_duration = doc.querySelector('video').length;
Web Audio API
When working with the Web Audio API, you would possibly load the Audio file in a number of methods. The most typical means is utilizing AJAX.
var ctx = new webkitAudioContext();
perform loadMusic(url) {
var req = new XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
req.onload = perform() {
ctx.decodeAudioData(req.response, perform(buffer) {
console.log(buffer);
console.log(buffer.length); // 116
})
};
req.ship();
}
We loaded the audio file utilizing XHR2 that helps the arraybuffer response sort. Some different methods would possibly embody utilizing the file enter area or the FileSystem API to fetch the file from after which learn that utilizing FileReader.readAsArrayBuffer().
So, when the Audio Data within the ArrayBuffer (within the XHR response) is decoded by ctx.decodeAudioData (async and non-blocking), the callback we handed to it will get known as. This callback receives, an AudioBuffer object that accommodates the length property which holds the length of the PCM Audio Data in seconds. This method appears to work high-quality on a video file too!
Note: In each the strategies mentioned above, the length worth is a float representing the time in seconds.
Recommended from our customers: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch.
HI-FI News
through Code Theory https://codetheory.in
January 6, 2024 at 11:30AM
-
Product on sale
Audiophile Vinyl Records Cleaning BundleOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Product on sale
Easy Start Vinyl Records Cleaning KitOriginal price was: €69.90.€59.90Current price is: €59.90. incl. VAT -
Vinyl Records Cleaner Easy Groove Concentrate€34.95 incl. VAT -
Easy Groove Super Set€199.00 incl. VAT -
Easy Groove Enzycaster – vinyl records prewash cleaner€34.95 incl. VAT -
Easy Groove Extreme MK. II- vinyl records prewash cleaner€45.00 incl. VAT -
Vinyl Records Cleaner – Easy Groove Virgin Concentrate€35.00 incl. VAT -
Easy Groove Spray&Wipe vinyl records cleaner€34.95 incl. VAT








