Benjamin
Benjamin

Reputation: 3950

HTMLMediaElement.duration returning NaN for audio file

I have the following JavaScript to play a sound when a button is clicked on the screen, however I'm only getting NaN for the duration.

$(document).ready(function() {
  function play_sound() {
    var audio = new Audio("assets/sound.ogg");
    audio.play();
    var duration = audio.duration;
    console.log(duration);
  }

  $(document).on("click", ".box", function(e) {
    play_sound();
  });
});

In my research I found this answer which uses the "loadeddata" event, however I'm not sure how to incorporate that into my code. Should I use an <audio> element in my HTML?

Upvotes: 3

Views: 1816

Answers (1)

MortenMoulder
MortenMoulder

Reputation: 6646

Here's my shot at it:

$(document).ready(function() {
    function play_sound() {
        var audio = new Audio("assets/sound.ogg");
        audio.addEventListener("loadedmetadata", function(_event) {
            var duration = audio.duration;
            console.log(duration);
        });

        audio.play();
    }

    $(document).on("click", ".box", function(e) {
        play_sound();
    });
});

http://jsfiddle.net/x2pe6hcf/1/

Added the eventListener and it works perfectly.

Upvotes: 4

Related Questions