AudioContext.resume()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2021.

AudioContextresume() 方法,恢复之前暂停播放的音频。

如果在 OfflineAudioContext 上调用,会导致 INVALID_STATE_ERR 错误。

语法

js
var audioCtx = new AudioContext();
audioCtx.resume().then(function() { ... });

结果

Promise成功的话返回空值,返回失败是因为 context 已经关闭了。

示例

下面的代码是 AudioContext states demo (see it running live) 的一部分。当点击暂停/恢复按钮的时候,需要AudioContext.state做判断:如果是运行状态,调用suspend(),如果是暂停状态,调用resume()。每次点击事件成功后,按钮的文字也会随着变成对应的状态

js
susresBtn.onclick = function () {
  if (audioCtx.state === "running") {
    audioCtx.suspend().then(function () {
      susresBtn.textContent = "Resume context";
    });
  } else if (audioCtx.state === "suspended") {
    audioCtx.resume().then(function () {
      susresBtn.textContent = "Suspend context";
    });
  }
};

规范

Specification
Web Audio API
# dom-audiocontext-resume

兼容性

BCD tables only load in the browser

参见