AudioBuffer: getChannelData() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

AudioBuffer 介面的 getChannelData() 方法返回一個 Float32Array,其中包含與通道關聯的 PCM 資料,由 channel 引數定義(0 代表第一個通道)。

語法

js
getChannelData(channel)

引數

channel

channel 屬性是一個索引,表示要獲取資料的特定通道。索引值 0 代表第一個通道。如果 channel 索引值大於或等於 AudioBuffer.numberOfChannels,則會丟擲 INDEX_SIZE_ERR 異常。

返回值

一個 Float32Array

示例

在以下示例中,我們建立一個兩秒的緩衝區,用白噪聲填充它,然後透過 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(2, 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-audiobuffer-getchanneldata

瀏覽器相容性

另見