Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 209
Benjamin Humphrey Avatar asked Dec 07 '25 22:12

Benjamin Humphrey


1 Answers

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.

like image 170
MortenMoulder Avatar answered Dec 10 '25 10:12

MortenMoulder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!