javascriptaudio

audio.duration is not trustworthy?


I have a JS program that plays an audio until the very end. I noticed than audio.duration slightly changes at the end of the audio, seemingly to have 0 <= audio.currentTime <= audio.duration always hold true :

let audio = new Audio(...)
audio.play()
function printAudioDuration() {
  window.requestAnimationFrame(() => {
    console.log(audio.duration)
    printAudioDuration()
  )
}
printAudioDuration()

That results in :

132.623667
132.623667
132.623667
...
132.623667
132.623673

And if I print audio.currentTime along the way, I always get a timestamp smaller than 132.623667, except for the last one, which exactly equals 132.623673.

Is this a documented behavior ? Am I doing something wrong ?


Solution

  • Yes, it is documented that the duration can be changed and there is an event posted if it is changed.

    The duration can be NaN, +Infinity or a finite number.

    From the documentation

    When the length of the media resource changes to a known value (e.g. from being unknown to known, or from a previously established length to a new length) the user agent must queue a media element task given the media element to fire an event named durationchange at the media element.