AudioBuffer接口表示存在存储器里的短音频资产,利用AudioContext.decodeAudioData()方法从音频文件构建,或者利用 AudioContext.createBuffer()构建于原数据。一旦将其放入AudioBuffer,可以传递到一个 AudioBufferSourceNode进行播放。
这些类型对象被设计来控制小音频片段,往往短于45秒。对于更长的声音,通过 MediaElementAudioSourceNode来实现更为合适。缓存区(buffer)包含以下数据:不间断的IEEE75432位线性PCM,从-1到1的范围额定,就是说,32位的浮点缓存区的每个样本在-1.0到1.0之间。如果AudioBuffer有不同的频道,他们通常被曝存在独立的缓存区。
属性
AudioBuffer.sampleRate只读- 存储在缓存区的PCM数据的采样率:浮点数,单位为 sample/s。
AudioBuffer.length只读- 返回存储在缓存区的PCM数据的采样帧率:整形。
AudioBuffer.duration只读- 返回存储在缓存区的PCM数据的时长:双精度型(单位为秒),。
AudioBuffer.numberOfChannels只读- 返回存储在缓存区的PCM数据的通道数:整形。
方法
AudioBuffer.getChannelData()- 返回一个
Float32Array,包含了带有频道的PCM数据,由频道参数定义(有0代表第一个频道) AudioBuffer.copyFromChannel()- 从AudioBuffer的指定频道复制到数组终端。
AudioBuffer.copyToChannel()- 复制样品到原数组的AudioBuffer的指定频道
例子
以下的例子展示了如何构建一个AudioBuffer以及随机用白噪音填充。你可以在 audio-buffer demo库发现完整的源代码;一个running live 的版本也可获得。
// Stereo
var channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
var frameCount = audioCtx.sampleRate * 2.0;
var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
button.onclick = function() {
// Fill the buffer with white noise;
// just random values between -1.0 and 1.0
for (var channel = 0; channel < channels; channel++) {
// This gives us the actual array that contains the data
var nowBuffering = myArrayBuffer.getChannelData(channel);
for (var 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
var 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 |
Working Draft | Initial definition. |
浏览器兼容性
| 特点 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| 基本支持 | 14 webkit | 25 (25) | 未实现 | 15 webkit 22 |
6 webkit |
copyFromChannel() and copyToChannel() |
? | 27 (27) | 未实现 | ? | 未实现 |
| Feature | Android | Chrome | Firefox Mobile (Gecko) | Firefox OS | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|---|
| Basic support | 未实现 | 28 webkit | 25.0 (25) | 1.2 | 未实现 | 未实现 | 6 webkit |
copyFromChannel() and copyToChannel() |
未实现 | ? | 27.0 (27) | 未实现 | 未实现 | 未实现 |