AudioBuffer: getChannelData() 方法
AudioBuffer 接口的 getChannelData() 方法返回一个 Float32Array,其中包含与通道关联的 PCM 数据,由 channel 参数定义(0 代表第一个通道)。
语法
js
getChannelData(channel)
参数
channel-
channel 属性是一个索引,表示要获取数据的特定通道。索引值 0 代表第一个通道。如果
channel索引值大于或等于AudioBuffer.numberOfChannels,则会抛出INDEX_SIZE_ERR异常。
返回值
一个 Float32Array。
示例
在以下示例中,我们创建一个两秒的缓冲区,用白噪声填充它,然后通过 AudioBufferSourceNode 播放它。注释应清楚地解释正在发生的事情。您也可以实时运行代码,或查看源代码。
js
const audioCtx = new AudioContext();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");
pre.textContent = myScript.textContent;
// 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;
}
}
// 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 # dom-audiobuffer-getchanneldata |
浏览器兼容性
加载中…