首页 > 解决方案 > AnalyserNode 如何(如果有的话)用于分析整个音频文件,并获取可视化所需的数据?

问题描述

特别是,我对这种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;
}

标签: javascripthtml5-canvasweb-audio-api

解决方案


您在主题中说您拥有整个文件。如果是这种情况,您可以对文件 ( decodeAudioData) 进行解码,您将获得一个包含所有样本的 AudioBuffer,然后您可以将其用于可视化。

如果您无法将整个文件解码到内存中,则必须使用不同的方法,并且AnalyserNode可能无法正常工作,因为它是异步的,因此您可能无法获得所有样本,或者您可能会得到重复。如果这是不可接受的,您可能必须使用MediaStreamAudioSourceNode连接到 a 的 aScriptProcessorNodeAudioWorkletNode来获取所需的时域数据。


推荐阅读