AudioBuffer

Baseline 已廣泛支援

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

AudioBuffer 介面表示駐留在記憶體中的短音訊資源,它可以透過 AudioContext.decodeAudioData() 方法從音訊檔案中建立,或透過 AudioContext.createBuffer() 從原始資料建立。一旦被放入 AudioBuffer,音訊就可以透過傳遞給 AudioBufferSourceNode 來播放。

這些型別的物件旨在儲存較小的音訊片段,通常小於 45 秒。對於較長的聲音,實現 MediaElementAudioSourceNode 的物件更為合適。緩衝區包含編碼為一系列幅度的音訊訊號波形,格式如下:非交錯的 IEEE754 32 位線性 PCM,標稱範圍在 -1+1 之間,也就是說,一個 32 位浮點緩衝區,每個樣本值在 -1.0 和 1.0 之間。如果 AudioBuffer 有多個通道,它們將儲存在單獨的緩衝區中。

建構函式

AudioBuffer()

建立並返回一個新的 AudioBuffer 物件例項。

例項屬性

AudioBuffer.sampleRate 只讀

返回一個浮點數,表示緩衝區中儲存的 PCM 資料的取樣率(每秒取樣數)。

AudioBuffer.length 只讀

返回一個整數,表示緩衝區中儲存的 PCM 資料的長度(以取樣幀為單位)。

AudioBuffer.duration 只讀

返回一個雙精度浮點數,表示緩衝區中儲存的 PCM 資料的持續時間(以秒為單位)。

AudioBuffer.numberOfChannels 只讀

返回一個整數,表示緩衝區中儲存的 PCM 資料所描述的離散音訊通道數。

例項方法

AudioBuffer.getChannelData()

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

AudioBuffer.copyFromChannel()

AudioBuffer 指定通道的樣本複製到 destination 陣列。

AudioBuffer.copyToChannel()

source 陣列的樣本複製到 AudioBuffer 指定的通道。

示例

以下簡單示例演示瞭如何建立 AudioBuffer 並用隨機白噪聲填充它。您可以在我們的 webaudio-examples 儲存庫中找到完整的原始碼;此外,還有一個 線上執行 的版本。

js
const audioCtx = new AudioContext();

// Create an empty three-second stereo buffer at the sample rate of the AudioContext
const myArrayBuffer = audioCtx.createBuffer(
  2,
  audioCtx.sampleRate * 3,
  audioCtx.sampleRate,
);

// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (let channel = 0; channel < myArrayBuffer.numberOfChannels; channel++) {
  // This gives us the actual array that contains the data
  const nowBuffering = myArrayBuffer.getChannelData(channel);
  for (let i = 0; i < myArrayBuffer.length; 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
# AudioBuffer

瀏覽器相容性

另見