javascript - 为什么在音频 src 上调用的 timeupdate 事件更改 HTML/JS

标签 javascript html5-audio

我的标记中有一个音频文件:

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

我也在使用 JS 创建我自己的音频播放器,显示当前时间和持续时间:

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

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

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

当用户与页面的某些元素交互时,我将更新音频源:

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

有趣的是,它将进入 ontimeupdate事件,即使音频之前已暂停。我想知道为什么会这样?当我更改音频的 src 时,为什么会触发 ontimeupdate 事件。

我在这里混合了 Vanilla JS 和 jQuery,但这应该没有任何区别。

最佳答案

我猜测更改 .src 属性会触发 media element load algorithm .

此算法的一部分(resource selection algorithm)需要更改播放位置:

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

此更改将触发 timeupdate事件:

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.

关于javascript - 为什么在音频 src 上调用的 timeupdate 事件更改 HTML/JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501027/

相关文章:

javascript - 在传递变量期间保持原始值

javascript音频加载不让它暂停

javascript - 是否可以检查用户是否有摄像头和麦克风以及是否已使用 Javascript 授予权限?

jquery - 具有全部播放功能的音频播放器

javascript - HTML5 : How to get currentTime and duration of Audio Tag in milliseconds

javascript - 如何从自定义钩子(Hook)验证中正确显示错误消息?

javascript - 在浏览器的子窗口中登录完成后通知父窗口

javascript - 如何在 iframe 中水平放置 PDF 文件?

javascript - Android 网络浏览器重新加载 HTML5 音频元素中的源文件 - 如何防止?

javascript - AngularJS - 从模型中设置选定的值