OfflineAudioContext: startRendering() 方法

Baseline 已广泛支持

此特性已得到良好支持,可在多种设备和浏览器版本上使用。自 2021 年 4 月起,所有浏览器均已支持此特性。

OfflineAudioContext 接口的 startRendering() 方法会启动音频图的渲染,并考虑当前的连接和已计划的更改。

当渲染完成时,会触发(类型为 OfflineAudioCompletionEvent 的)complete 事件,该事件会在其 renderedBuffer 属性中包含渲染后的 AudioBuffer

浏览器目前支持 startRendering() 方法的两个版本 — 一个是旧的基于事件的版本,另一个是较新的基于 Promise 的版本。前者最终将被移除,但目前出于向后兼容的考虑,两种机制都已提供。

语法

js
startRendering()

参数

无。

返回值

一个 fulfilled 为 AudioBufferPromise

示例

使用离线音频上下文播放音频

在此示例中,我们声明了一个 AudioContext 和一个 OfflineAudioContext 对象。我们使用 AudioContext 通过 fetch() 加载一个音频轨道,然后使用 OfflineAudioContext 将音频渲染到 AudioBufferSourceNode 中并播放该轨道。在设置好离线音频图之后,我们使用 OfflineAudioContext.startRendering() 将其渲染为一个 AudioBuffer

startRendering() Promise 解析时,渲染即完成,输出的 AudioBuffer 将从 Promise 中返回。

此时,我们创建另一个音频上下文,在其中创建一个 AudioBufferSourceNode,并将其 buffer 设置为与 Promise 中的 AudioBuffer 相同。然后,它将作为简单标准音频图的一部分进行播放。

注意:您可以 实时运行完整的示例,或者 查看源代码

js
// Define both online and offline audio contexts
let audioCtx; // Must be initialized after a user interaction
const offlineCtx = new OfflineAudioContext(2, 44100 * 40, 44100);

// Define constants for dom nodes
const play = document.querySelector("#play");

function getData() {
  // Fetch an audio track, decode it and stick it in a buffer.
  // Then we put the buffer into the source and can play it.
  fetch("viper.ogg")
    .then((response) => response.arrayBuffer())
    .then((downloadedBuffer) => audioCtx.decodeAudioData(downloadedBuffer))
    .then((decodedBuffer) => {
      console.log("File downloaded successfully.");
      const source = new AudioBufferSourceNode(offlineCtx, {
        buffer: decodedBuffer,
      });
      source.connect(offlineCtx.destination);
      return source.start();
    })
    .then(() => offlineCtx.startRendering())
    .then((renderedBuffer) => {
      console.log("Rendering completed successfully.");
      play.disabled = false;
      const song = new AudioBufferSourceNode(audioCtx, {
        buffer: renderedBuffer,
      });
      song.connect(audioCtx.destination);

      // Start the song
      song.start();
    })
    .catch((err) => {
      console.error(`Error encountered: ${err}`);
    });
}

// Activate the play button
play.onclick = () => {
  play.disabled = true;
  // We can initialize the context as the user clicked.
  audioCtx = new AudioContext();

  // Fetch the data and start the song
  getData();
};

规范

规范
Web Audio API
# dom-offlineaudiocontext-startrendering

浏览器兼容性

另见