音频开发 / 系统课时

用用户操作启动音频上下文

用用户操作启动音频上下文

浏览器通常不会允许页面在没有用户交互时直接发声。本节用一次按钮点击恢复 AudioContext,再播放一个短音作为验证,建立“用户手势 → 恢复上下文 → 创建声源 → 输出声音”的最小可用链路。

学习目标

  • 理解 AudioContext 为什么可能处于 suspended 状态
  • 在点击事件中调用 resume() 并等待上下文进入可播放状态
  • 用短音和 state 输出验证恢复是否成功

为什么页面加载后不能直接发声

浏览器的自动播放策略会限制未经用户明确操作触发的声音。即使代码已经创建了 AudioContext,它也可能停留在 suspended,此时节点图已经存在,却不会正常输出可听声音。

因此不要把“创建上下文”和“允许播放”视为同一件事。更稳妥的做法是把恢复动作放进点击、触摸或键盘等真实用户操作的事件处理函数里,并在恢复完成后再启动声源。

在按钮点击中恢复并播放

下面是一个可直接保存为 index.html 后在浏览器打开的完整示例。点击按钮时先调用 resume(),再创建一次性的振荡器并播放 250 毫秒。

html
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Resume AudioContext</title>
</head>
<body>
  <button id="playButton">启动并播放</button>

  <script>
    const audioContext = new AudioContext();
    const playButton = document.querySelector("#playButton");

    playButton.addEventListener("click", async () => {
      // 用户手势内恢复上下文,避免自动播放策略阻止声音输出。
      if (audioContext.state === "suspended") {
        await audioContext.resume();
      }

      const oscillator = audioContext.createOscillator();
      const gain = audioContext.createGain();

      oscillator.frequency.value = 440;
      gain.gain.value = 0.08;

      oscillator.connect(gain).connect(audioContext.destination);

      const now = audioContext.currentTime;
      oscillator.start(now);
      oscillator.stop(now + 0.25);

      console.log(`state after resume: ${audioContext.state}`);

      oscillator.addEventListener("ended", () => {
        oscillator.disconnect();
        gain.disconnect();
        console.log("tone finished");
      }, { once: true });
    });
  </script>
</body>
</html>

预期输出

text
state after resume: running
tone finished

同时应听到约 250 毫秒的 440 Hz 短音。浏览器控制台中的第二行会在短音结束后出现。

验证和排查

先在页面加载后查看 audioContext.state。如果它是 suspended,属于常见情况;点击按钮后应变为 running。如果点击后仍没有声音,按以下顺序检查:系统或标签页是否静音、事件是否由真实点击触发、节点是否最终连接到 audioContext.destination。

OscillatorNode 只能启动一次,所以每次点击都应新建一个振荡器;不要尝试对已经停止的实例再次调用 start()。长期运行的应用则可以复用同一个 AudioContext,避免频繁创建和关闭上下文。

何时需要再次调用 resume

页面切换后台、系统节能或浏览器策略都可能让上下文再次暂停。应用在准备播放前检查 audioContext.state,发现为 suspended 时再在用户操作中调用 resume(),比只在页面初始化时恢复一次更稳健。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

用用户操作启动音频上下文

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通