gpt4 book ai didi

javascript - 暂停模式周围的静音 AudioContext 警告

转载 作者:行者123 更新时间:2023-12-02 22:52:39 25 4
gpt4 key购买 nike

我有一些 JS 代码如下所示:

class AudioSample {
constructor(volume = 1, playbackRate = 1) {
this.context = new AudioContext();
}

load(arrayBuffer) {
return new Promise((resolve, reject) => {
this.context.decodeAudioData(
arrayBuffer,
buffer => {
this.buffer = buffer;

resolve(buffer);
},
reject
);
});
}
// Other stuff
}

// When the page loads
const sample = new AudioSample();

fetch('/some-sound.mp3')
.then(res => res.arrayBuffer())
.then(arrayBuffer => sample.load(arrayBuffer));

// When a button is clicked
const play = () => {
sample.current.pause();
sample.current.setCurrentTime(0);
sample.current.play();
};

此代码按预期工作;当页面加载时,它会获取并准备声音。单击按钮时,会播放声音(即使是第一次)。

我的问题是在 Chrome 控制台中记录了以下警告:

The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio

这个警告有点问题,因为我想打包这个小实用程序,但我不希望我的 NPM 包抛出转移注意力的警告!

有没有办法告诉浏览器“我知道,别担心,在用户与页面交互之前我不会播放声音”?

最佳答案

对于 chrome,消除警告的唯一方法是根据用户手势创建上下文。另见 chrome bug 943258

如果修复了该错误,那就太好了。正如错误所说,在没有手势的情况下创建上下文并没有错。只恢复不做手势是错误的。

关于javascript - 暂停模式周围的静音 AudioContext 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787836/

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