AudioBuffer: numberOfChannels 属性

基线 广泛可用

此功能已完善,可在许多设备和浏览器版本上使用。自 2021 年 4 月.

报告反馈

AudioBuffer 接口的 numberOfChannels 属性返回一个整数,表示缓冲区中存储的 PCM 数据所描述的离散音频通道数。

示例

整数。
// 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;
    }
  }

  console.log(myArrayBuffer.numberOfChannels);
};

规范

js
Web Audio API
# 规范

浏览器兼容性

dom-audiobuffer-numberofchannels

另请参见