暂停模式周围的静音 AudioContext 警告
Silencing AudioContext warning around suspended mode
我有一些 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 包抛出转移注意力的警告!
有没有办法告诉浏览器"I know, don't worry, I won't play the sound until a user interacts with the page"?
对于 chrome,消除警告的唯一方法是根据用户手势创建上下文。另见 chrome bug 943258
如果那个错误被修复就好了。正如错误所说,在没有手势的情况下创建上下文并没有错。只恢复不做手势是错误的。
我有一些 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 包抛出转移注意力的警告!
有没有办法告诉浏览器"I know, don't worry, I won't play the sound until a user interacts with the page"?
对于 chrome,消除警告的唯一方法是根据用户手势创建上下文。另见 chrome bug 943258
如果那个错误被修复就好了。正如错误所说,在没有手势的情况下创建上下文并没有错。只恢复不做手势是错误的。