Search code examples
javascriptweb-audio-api

What are the frequencies in Hertz of the "bins" that AnalyserNode.getByteFrequencyData() returns?


I am currently working on a project that uses JavaScript's WebAudio API to show a graph of the frequencies in the audio. AnalyserNode.getByteFrequencyData() fills an Array which is divided into "bins", each with a frequency range. I would like to know what frequencies (measured in Hertz) those "bins" correspond to.

I've tried interpreting each bin as a 1Hz step, but that clearly isn't right.


Solution

  • From the MDN docs for AnalyserNode.getByteFrequencyData() (emphasis mine):

    Each item in the array represents the decibel value for a specific frequency. The frequencies are spread linearly from 0 to 1/2 of the sample rate. For example, for 48000 sample rate, the last item of the array will represent the decibel value for 24000 Hz.

    To calculate the frequencies, we need the sample rate. This can be obtained from the sampleRate property on the AudioContext (inherited from BaseAudioContext):

    The sampleRate property of the BaseAudioContext interface returns a floating point number representing the sample rate, in samples per second, used by all nodes in this audio context. (docs)


    You can set the sample rate of an AudioContext when it is created, via the options parameter of the constructor.

    You can set the window size of the FFT of an AudioAnalyzer at creation via the options parameter of the constructor and any time after via the fftSize property. From the docs for AnalyserNode.fftSize:

    The fftSize property of the AnalyserNode interface is an unsigned long value and represents the window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.