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

瀏覽器相容性

另見