如何在 Typescript 中使用 AnalyzerNode 处理 wav 文件?

How to process a wav file with an AnalyzerNode in Typescript?

我正在尝试计算 Typescript 中 wav 文件的快速傅里叶变换。

我正在考虑为此使用专用的 npm 包,like fft.js, but then I noticed that the standard AnalyzerNode 具有内置的 FFT 功能。但是,我只见过AnalyzerNode用于处理实时音频流。

您如何向它发送从通用 wav 文件加载的数据,无论是从文件系统还是从任何其他来源(例如 wav 解码器)加载,而不是麦克风?

首先,请注意 AnalyserNode 只给出了 FFT 的幅度;阶段部分不包括在内。但是,如果这对您有用,那么您可以使用 OfflineAudioContextsuspend(time) 来获取 FFT(幅度)。类似于:

// Let f be the file that has the wav file.
// c is used only so we can run decodeAudioData.  There are other ways to 
// do this.
let c = new AudioContext();
let b = await fetch(f)
  .then(response => response.arrayBuffer())
  .then(buffer => c.decodeAudioData(buffer));

let oac = new OfflineAudioContext({
  numberOfChannels: b.numberOfChannels,
  length: b.length,
  sampleRate: b.sampleRate});

let a = new AnalyserNode(oac, {fftSize: 1024});

// Suspend the context every fftSize frames so we can get the FFT of 
// the previous fftSize frames.
for (let k = a.fftSize; k < b.length; k += a.fftSize) {
  oac.suspend(k / b.sampleRate)
    .then(() => {
      a.getFloatFrequencyData(fftData);
      // Copy fftData out or do something with it
      });
    .then(() => oac.resume());
}

// We can ignore the buffer that startRendering would return from the
// resolved promise.
await oac.startRendering();