BaseAudioContext:createBufferSource() 方法

Baseline 已廣泛支援

此特性已得到良好支援,可在多種裝置和瀏覽器版本上使用。自 2021 年 4 月起,所有瀏覽器均已支援此特性。

BaseAudioContext 介面的 createBufferSource() 方法用於建立一個新的 AudioBufferSourceNode,該節點可用於播放包含在 AudioBuffer 物件中的音訊資料。AudioBuffer 物件透過 BaseAudioContext.createBuffer 建立,或者在成功解碼音訊軌道時由 BaseAudioContext.decodeAudioData 返回。

注意: AudioBufferSourceNode() 建構函式是建立 AudioBufferSourceNode 的推薦方式;請參閱 建立 AudioNode

語法

js
createBufferSource()

引數

無。

返回值

一個 AudioBufferSourceNode

示例

在此示例中,我們建立一個兩秒的緩衝區,用白噪聲填充它,然後透過 AudioBufferSourceNode 播放它。註釋應清楚地解釋正在發生的事情。

注意: 您也可以 線上執行程式碼,或者 檢視原始碼

js
const audioCtx = new AudioContext();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");

pre.textContent = myScript.textContent;

// Stereo
const channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
const frameCount = audioCtx.sampleRate * 2.0;

const myArrayBuffer = audioCtx.createBuffer(
  channels,
  frameCount,
  audioCtx.sampleRate,
);

button.onclick = () => {
  // Fill the buffer with white noise;
  // just random values between -1.0 and 1.0
  for (let channel = 0; channel < channels; channel++) {
    // This gives us the actual ArrayBuffer that contains the data
    const nowBuffering = myArrayBuffer.getChannelData(channel);
    for (let i = 0; i < frameCount; i++) {
      // Math.random() is in [0; 1.0]
      // audio needs to be in [-1.0; 1.0]
      nowBuffering[i] = Math.random() * 2 - 1;
    }
  }

  // Get an AudioBufferSourceNode.
  // This is the AudioNode to use when we want to play an AudioBuffer
  const source = audioCtx.createBufferSource();
  // set the buffer in the AudioBufferSourceNode
  source.buffer = myArrayBuffer;
  // connect the AudioBufferSourceNode to the
  // destination so we can hear the sound
  source.connect(audioCtx.destination);
  // start the source playing
  source.start();
};

規範

規範
Web Audio API
# dom-baseaudiocontext-createbuffersource

瀏覽器相容性

另見