Search code examples
javascripthtml5-audio

Why is the timeupdate event called on audio src change HTML / JS


I have an audio file in my markup:

<audio class="audio-player">
  <source src="audio/scene_1.wav" type="audio/wav" />
</audio>

I am also using JS to create my own audio player with a display of the current time and duration:

let audio = $('.audio-player')[0]

audio.ontimeupdate = () => {
  console.log("updated")

  $('.audio-seconds').html(`
    0:0${Math.floor(audio.currentTime)} / 0:${Math.floor(audio.duration)}
  `)
}

When the user interacts with certain elements of the page I will update the audio src:

$('.audio-player').attr('src', `audio/scene_${g.currentScene.next}.wav`)

Interestingly it will go into the ontimeupdate event even though the audio was paused before. I'm wondering why this is happening? When I change the src of an audio, why is it triggering the ontimeupdate event.

I am mixing Vanilla JS and jQuery here but that should not make any difference at all.


Solution

  • I would guess that changing the .src attribute triggers the media element load algorithm.

    Part of this alogrithm (the resource selection algorithm) requires to change the playback position:

    1. Set the current playback position and the official playback position to the earliest possible position.

    This change will trigger an timeupdate event:

    When the earliest possible position changes, then: if the current playback position is before the earliest possible position, the user agent must seek to the earliest possible position; otherwise, if the user agent has not fired a timeupdate event at the element in the past 15 to 250ms and is not still running event handlers for such an event, then the user agent must queue a task to fire an event named timeupdate at the element.