【发布时间】:2020-05-04 08:52:51
【问题描述】:
我有一些看起来像这样的 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 控制台中记录了以下警告:
AudioContext 不允许启动。它必须在页面上的用户手势之后恢复(或创建)。 https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio
这个警告有点问题,因为我想打包这个小实用程序,但我不希望我的 NPM 包抛出红鲱鱼警告!
有没有办法告诉浏览器“我知道,别担心,在用户与页面交互之前我不会播放声音”?
【问题讨论】:
-
您可以获取 mp3 数组缓冲区,而无需在页面加载时创建 AudioContext。然后当用户点击播放创建上下文并在播放声音之前调用 sample.load。我认为没有其他方法可以消除警告
-
明白了,谢谢。是的,我会这样做的。
标签: javascript audio web-audio-api