Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading mp3 file duration in Chrome with JavaScript/jQuery

I have an 'browser application' where users should be able to drag and drop local mp3 files to Chrome and should see some mp3 info (without uploading files to server)...
So far, I can successfully read and display mp3 tags (with JavaScript-ID3-Reader library), but I'm struggling a bit with displaying mp3's duration. Is it possible to get that info with js/jQuery only? If not, what would you recommend for resolving this simple problem?

Code I'm using to handle dropping files to browser looks like this:

function initialize() {
    var target = document;
    if (target === null) {
        return false;
    }

    target.addEventListener('drop', function(event) {
        event.preventDefault();
        var files = event.dataTransfer.files;
        console.log(files);
        for (var i = 0; i < files.length; i++) {
            processFile(files[i]);
            objectURL = window.URL.createObjectURL(files[i]);
            console.log(objectURL);
        }
    }, true);
}

Thanks!

like image 565
errata Avatar asked Aug 08 '26 11:08

errata


1 Answers

Try this

var audio = new Audio()
audio.addEventListener("timeupdate", function() {
  console.log(audio.currentTime)
})
audio.addEventListener("canplaythrough", function() {
  console.log(audio.duration)
})

target.on("change", function(e) {
    var file = e.currentTarget.files[0]
    var objectUrl = URL.createObjectURL(file)
    audio.src = objectUrl
    $("#duration").html(audio.duration)
})
like image 120
Dima Melnik Avatar answered Aug 10 '26 00:08

Dima Melnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!