errata
errata

Reputation: 6031

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!

Upvotes: 3

Views: 3906

Answers (2)

Dima Melnik
Dima Melnik

Reputation: 884

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)
})

Upvotes: 3

closure
closure

Reputation: 7452

If you are using latest browsers that support audio tag, you can load the mp3 in an <audio> element and access the duration property via the DOM.

To load a audio file to browser see: window.URL.createObjectURL

Upvotes: 1

Related Questions