AudioBuffer:sampleRate 属性

基线 广泛可用

此功能已在许多设备和浏览器版本中广泛使用,并且运行良好。它已从 2021 年 4 月.

报告反馈

sampleRate 属性是 AudioBuffer 接口的属性,它返回一个表示缓冲区中存储的 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.sampleRate);
};

规范

js
Web 音频 API
# 规范

浏览器兼容性

dom-audiobuffer-samplerate

另请参阅