尤其是我对AnalyserNode.getFloatTimeDomainData()
方法感兴趣。
我可以使用此方法来创建代表整个音频文件的波形吗?
或者AnalyserNode仅用于音频流吗?
MDN文档说:
AnalyserNode接口表示一个能够提供实时频率和时域分析信息的节点。它是一个AudioNode,它将音频流从输入不变地传递到输出,但是允许您获取生成的数据,对其进行处理并创建音频可视化。
https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode
所有示例似乎都使用AudioBuffer.getChannelData()
来获取用于可视化整个音频文件的数据。如本文所述:
https://css-tricks.com/making-an-audio-waveform-visualizer-with-vanilla-javascript/
摘自文章:
const filterData = audioBuffer => {
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
const samples = 70; // Number of samples we want to have in our final data set
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
const filteredData = [];
for (let i = 0; i < samples; i++) {
let blockStart = blockSize * i; // the location of the first sample in the block
let sum = 0;
for (let j = 0; j < blockSize; j++) {
sum = sum + Math.abs(rawData[blockStart + j]) // find the sum of all the samples in the block
}
filteredData.push(sum / blockSize); // divide the sum by the block size to get the average
}
return filteredData;
}
您在主题中说,您拥有整个文件。如果是这种情况,您可以对文件(decodeAudioData
)进行解码,并且会获得一个AudioBuffer以及所有样本,然后可以将它们用于可视化。
如果无法将整个文件解码到内存中,则必须使用其他方法,并且AnalyserNode
可能不起作用,因为它是异步的,因此您可能无法获取所有样本,也可能会得到重复的样本。如果这是不可接受的,则可能必须使用连接到MediaStreamAudioSourceNode
或ScriptProcessorNode
的AudioWorkletNode
来获取所需的时域数据。