gpt4 book ai didi

javascript - 音频文件在线时,如何在HTML5音频对象中设置currentTime?

转载 作者:数据小太阳 更新时间:2023-10-29 04:51:53 33 4
gpt4 key购买 nike

我有一个带有向前/向后跳过 10 秒按钮的 JavaScript 音频播放器。我通过设置音频元素的 currentTime 来做到这一点:

function Player(skipTime)
{
this.skipTime = skipTime;
this.waitLoad = false;

// initialise main narration audio
this.narration = new Audio(getFileName(dynamicNarration));
this.narration.preload = "auto";
this.narration.addEventListener('canplaythrough', () => { this.loaded(); });
this.narration.addEventListener('timeupdate', () => { this.seek(); });
this.narration.addEventListener('ended', () => { this.ended(); });
this.narration.addEventListener('waiting', () => { this.audioWaiting(); });
this.narration.addEventListener('playing', () => { this.loaded(); });
}

Player.prototype = {
rew: function rew()
{
if (!this.waitLoad) {
this.skip(-this.skipTime);
}
},

ffw: function ffw()
{
if (!this.waitLoad) {
this.skip(this.skipTime);
}
},

skip: function skip(amount)
{
const curTime = this.narration.currentTime;
const newTime = curTime + amount;
console.log(`Changing currentTime (${curTime}) to ${newTime}`);
this.narration.currentTime = newTime;
console.log(`Result: currentTime = ${this.narration.currentTime}`);
},

loaded: function loaded()
{
if (this.waitLoad) {
this.waitLoad = false;
playButton.removeClass('loading');
}
},

audioWaiting: function audioWaiting()
{
if (!this.waitLoad) {
this.waitLoad = true;
playButton.addClass('loading');
}
},
}

(我在这里包括了一些我附加的事件监听器,因为之前我调试了一个类似的问题,因为事件监听器中存在冲突。虽然这次彻底调试了事件监听器,但我不 < em>认为这就是问题的根源。)

虽然这在我的本地副本上一切正常,但当我测试在线版本时,我得到以下结果:

  • Chrome: 将播放位置重置为 0。最终控制台行显示结果:currentTime = 0
  • Safari:根本不改变播放位置。最后的 console.log 行为 currentTime 提供了一个等于 newTime 的值(即使播放位置实际上没有改变)。
  • Firefox: 跳过工作;向后跳会中断音频几秒钟,然后它会从播放头之前的几秒钟再次开始播放。在这两种情况下,最后的 console.log 行为 currentTime 提供了一个等于 newTime
  • 的值

问题一定与音频加载方式有关。我尝试添加另一个控制台日志行来显示 buffered 的开始和结束值。

在 Chrome 中,它会在当前播放位置后上升到 2 秒。在 Safari 中,它会上升到 ~170 秒,而在 Firefox 中,它似乎可以缓冲整个音频长度。

但是,在每种情况下,缓冲 对象的开始都是0

有谁知道可能出了什么问题吗?

最佳答案

正确加载音频文件和使用属性有一些要求。您在提供文件时的响应需要包含以下 header 。

接受范围:字节

内容长度:BYTE_LENGTH_OF_YOUR_FILE

内容范围:字节 0-BYTE_LENGTH_OF_YOUR_FILE/BYTE_LENGTH_OF_YOUR_FILE

内容类型:音频/mp3

我和我的同事们为此苦苦挣扎了几天,终于成功了

Image of Response header for an audio file

关于javascript - 音频文件在线时,如何在HTML5音频对象中设置currentTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137963/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com