Firefox:箭头键不计为用户手势,因此无法播放 AudioContext

问题描述 投票:0回答:1

我正在编写一个游戏,玩家使用箭头键进行交互,这可以产生音频。这适用于除 Firefox 之外的所有浏览器。

Firefox 似乎没有将箭头键(

ArrowUp
ArrowLeft
ArrowRight
ArrowDown
)视为有效的用户手势,这会阻止播放音频上下文。 Firefox 将其他键(例如
W
/
A
/
S
/
D
)视为有效键,但不包括箭头键。

控制台打印以下错误:

AudioContext 无法自动启动。它必须在用户在页面上做出手势后创建或恢复。

但是,箭头键在 Chrome 和 Safari 中被视为用户手势,并且音频播放正常。

有没有我可以使用的已知跨浏览器解决方案或解决方法?我知道我可以在游戏开始时放一个按钮,但我对游戏的艺术愿景就是在玩游戏之前没有一个大的开始按钮。

也许这是一个已知的 Firefox 错误,但我只是找不到它,或者也许有人知道解决方法。

总长:

重现步骤:

    前往演示网站
  1. 按上/下/左/右箭头
预期结果:声音将在所有浏览器中播放

实际结果:仅在 Safari 和 Chrome 中播放声音,Firefox 中不播放

演示代码:

<code>press a key to see if it sounds: </code> <script> const code = document.querySelector('code') const audioCtx = new AudioContext({}) const oscillatorGainNode = audioCtx.createGain() oscillatorGainNode.gain.value = 0.2 oscillatorGainNode.connect(audioCtx.destination) const beep = () => { const oscillator = audioCtx.createOscillator() oscillator.type = "square" oscillator.frequency.value = 220 + ((Math.random() * 9) | 0) * 32 const msDelay = 0 const msDuration = 200 oscillatorGainNode.connect(audioCtx.destination) oscillator.connect(oscillatorGainNode) oscillator.start(audioCtx.currentTime + msDelay / 1000) oscillator.stop(audioCtx.currentTime + msDelay / 1000 + msDuration / 1000) } window.onkeydown = (ev=> { beep() code.textContent+=ev.key + ' ' }) </script>
演示也托管在此 URL:

https://6643defaf1a25706487ec3f8--glittery-dusk-6bb447.netlify.app/

javascript firefox dom-events web-audio-api
1个回答
0
投票
我认为这可以被认为是 Firefox 中的一个错误。该规范 (

https://html.spec.whatwg.org/multipage/interaction.html#user-activation-processing-model) 包含以下文本:

激活触发输入事件是其

isTrusted

 的任何事件
属性为 true 并且其 
type
 是以下之一:

"keydown"

,前提是该键既不是 Esc 键,也不是用户代理保留的快捷键;
...

也许有人会说箭头键可以被视为快捷键,因为它们有时允许导航表单字段。

© www.soinside.com 2019 - 2024. All rights reserved.