AudioContext.suspend()

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.

AudioContext 接口的suspend() 方法暂停音频上下文对象中的进度,并暂时剥离进程对音频设备硬件的访问权限,减少 CPU 和电池的使用。当程序在一段时间内不会使用音频上下文对象时,这个方法对减少硬件资源占用是非常有用的。

若对OfflineAudioContext 调用此方法,将会抛出 INVALID_STATE_ERR 错误。

Syntax

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

Returns

A Promise that resolves with void. The promise is rejected if the context has already been closed.

Example

The following snippet is taken from our AudioContext states demo (see it running live.) When the suspend/resume button is clicked, the AudioContext.state is queried — if it is running, suspend() is called; if it is suspended, resume is called. In each case, the text label of the button is updated as appropriate once the promise resolves.

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";
    });
  }
};

Specifications

Specification
Web Audio API
# dom-audiocontext-suspend

Browser compatibility

BCD tables only load in the browser

See also