Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 audio duration using jQuery

Tags:

html

I am trying to get the audio duration using jQuery but having hard time getting it. The method I am using is defined below

var audioElement = document.createElement('audio');            
        audioElement.setAttribute('src','song.mp3');            
           audioElement.play();
           var duration = audioElement.duration;
               $(".songtime").html(duration);

But it says nan Does anybody have any idea how to solve this?

like image 814
josh Avatar asked Sep 25 '11 07:09

josh


3 Answers

Since the audio isn't still loaded, you need to wait until your element has the metadata loaded, there is a simple way to do it:

audioElement.addEventListener("loadedmetadata", function(_event) {
    var duration = audioElement.duration;
    //TODO whatever
});
like image 68
Albertoimpl Avatar answered Oct 04 '22 17:10

Albertoimpl


Probably issue is not valid any more but issue is that audio doesnt load file yet. You should add event when file is loaded

 $(audioElement).on("canplay", function () {
        alert(this.duration);
    });
like image 28
Vova Bilyachat Avatar answered Oct 04 '22 15:10

Vova Bilyachat


You are trying to read the duration before the audio file has been loaded. You have to wait until the browser knows what the duration is (i.e. after it has had time to download the file header).

like image 35
Quentin Avatar answered Oct 04 '22 17:10

Quentin