javascript - 如何在每次点击按钮时发出蜂鸣声

标签 javascript html beep javascript-oscillator

Html 应用程序需要在每次触摸按钮时发出蜂鸣声。

在桌面和 Android 浏览器中尝试了以下代码。

在桌面浏览器(最新的 Chrome)中快速点击 100 次后 点击 100 次后,按钮蜂鸣声将被禁用。

在移动浏览器(Android 11 或 8 Zebra Enterprise Browser)中,触摸按钮 10 次后蜂鸣声停止。

Chrome 控制台日志不包含任何警告或错误消息。它显示蜂鸣消息,但未发出蜂鸣声。

如何解决此问题,以便在每次单击或触摸按钮时都会发出蜂鸣声?

<html>
<head>
<script>
function beep () {
  const audioCtx = new (window.AudioContext || window.webkitAudioContext)()
  const oscillator = audioCtx.createOscillator()
  const gainNode = audioCtx.createGain()
  oscillator.connect(gainNode)
  gainNode.connect(audioCtx.destination)
  gainNode.gain.value = 1 // volume;
  oscillator.frequency.value = 3000 // frequency;
  oscillator.type = 'sine' // type;
  console.log('beep')
  oscillator.start()
  setTimeout(
    function () {
      oscillator.stop()
    },
    70 // duration
  )
}
</script>
</head>

<body>

<button type="button" onclick="beep()">
+
</button>
</body>
</html>

最佳答案

在一定次数的单击或触摸后蜂鸣声停止的原因是每次单击按钮时都会创建音频上下文,并且可以创建的音频上下文的数量有限制。

要解决此问题,您可以在蜂鸣功能之外仅创建一次音频上下文,并在每次单击按钮时重复使用它。

<html>
    <head>
        <script>
        const audioCtx = new (window.AudioContext || window.webkitAudioContext)()
        const gainNode = audioCtx.createGain()
        gainNode.connect(audioCtx.destination)
        gainNode.gain.value = 1 // volume;

        function beep () {
            const oscillator = audioCtx.createOscillator()
            oscillator.connect(gainNode)
            oscillator.frequency.value = 3000 // frequency;
            oscillator.type = 'sine' // type;
            console.log('beep')
            oscillator.start()
            setTimeout(
                function () {
                    oscillator.stop()
                },
                70 // duration
            )
        }
        </script>
    </head>

    <body>
        <button type="button" onclick="beep()">+</button>
    </body>
</html>

关于javascript - 如何在每次点击按钮时发出蜂鸣声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76124758/

相关文章:

javascript - Ember 数据 RestAdapter 嵌入了 hasMany

Javascript 页面重绘在 touchmove 事件期间暂停

文本字段中的 JavaScript 文本未获取值

html - 在 CSS3 中,使用 `transparency` 和 `gradient` 不起作用?

C++ WIN32 : where to put code that executes as program is running

audio - C#避免在按下KeyDown时发出哔哔声?

c# - 有些键盘比其他键盘更啰嗦吗?

javascript - 使用 eval() 定义变量显示未定义错误

html - 是否可以在 li 标签中使用不同的列表说明符

javascript - $state.go() 之后触发事件