josh
josh

Reputation: 96

HTML5 audio duration using jQuery

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?

Upvotes: 5

Views: 21625

Answers (4)

Albertoimpl
Albertoimpl

Reputation: 321

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

Upvotes: 10

Vova Bilyachat
Vova Bilyachat

Reputation: 19514

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

Upvotes: 5

Jim Jeffers
Jim Jeffers

Reputation: 17930

Others have had this issue and it looks like Safari can get thrown off if your web server does not send the proper HTTP header tags. I am having the same issue -- my demo was loading and playing the audio just fine but the duration always returned 'infiniti' due to the http headers my local server was using to serve the mp3 file.

The basic gist is that the content-type should be as follows:

Content-Type:audio/mpeg; name="name_of_file.mp3"

Instead of:

Content-Type:application/octet-stream 

For more info see the original post here: http://groups.google.com/group/jplayer/browse_thread/thread/256d29fcc158f8ec

Upvotes: 1

Quentin
Quentin

Reputation: 944546

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

Upvotes: 3

Related Questions