Rooban M Rooban M - 1 year ago 103
HTML Question

Audio duration returns NaN need some modification to run the player

Whenever I run the script it returns

NaN
for audio duration.

Script

var mytrack = document.getElementById('mytrack');
var duration1 = document.getElementById('fullDuration');
duration1.innerHTML = parseInt(mytrack.duration);


HTML

<audio id="mytrack" controls autoplay>
<source src="kalimba.mp3" type="audio/mp3" />
</audio>
<span id="fullDuration">0:00</span>

Answer Source

It is always advised to use the event of loadedmetadata and then calling them will always work. Using Event Listeners are best in this case.

var a = document.getElementById('mytrack');
a.addEventListener("loadedmetadata", function() {
  var duration1 = document.getElementById('fullDuration');
  duration1.innerHTML = parseInt(a.duration);
}, true);

This waits till the media is loaded and then it sets the contents of the <span> tag. For best results, please put this code either in the end of the document, before </body> tag or use window's load event:

document.addEventListener('DOMContentLoaded', function () {
  var a = document.getElementById('mytrack');
  a.addEventListener("loadedmetadata", function() {
    var duration1 = document.getElementById('fullDuration');
    duration1.innerHTML = a.duration;
  }, true);
}, false);

As said in comments, there's also another way to do it using preload attribute:

This enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience.

But since you already haveautoplay attribute, I guess preload won't be necessary.

The autoplay attribute has precedence over preload. If autoplay is specified, the browser would obviously need to start downloading the audio for playback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download