HTML5 sound duration using jQuery

I am trying to get the duration of the sound using jQuery, but having difficulty getting it. The method I use is defined below

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

But he says nan Does anyone have any ideas how to solve this?

+4
source share
4 answers

Since the sound is not loaded yet, you need to wait until your item has metadata loaded, there is an easy way to do this:

 audioElement.addEventListener("loadedmetadata", function(_event) { var duration = audioElement.duration; //TODO whatever }); 
+9
source

Probably the problem is no longer valid, but the problem is that the audio is not downloading the file yet. You must add an event when the file is uploaded.

  $(audioElement).on("canplay", function () { alert(this.duration); }); 
+4
source

You are trying to read the duration before downloading the audio file. You need to wait until the browser finds out what the duration is (i.e., after it has managed to download the file header).

+3
source

Others have this problem, and it looks like Safari might be reset if your web server doesn't send the correct HTTP header tags. I have the same problem: my demo was loading and playing sound just fine, but the duration always returned "infiniti" due to the http headers that my local server used to serve the mp3 file.

The main point is that the content type should be as follows:

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

Instead:

 Content-Type:application/octet-stream 

Read more here: http://groups.google.com/group/jplayer/browse_thread/thread/256d29fcc158f8ec

+1
source

All Articles