AudioBuffer
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 存储库中找到完整的源代码;此外,还有一个 在线运行 的版本。
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 |
浏览器兼容性
加载中…