Calculate the frequency with spectrum data

Hello,
I have managed to get the spectrum data but I am a bit confused on how to calculate the frequency from those values. I’ve read somewhere in the forums that it is the number of entries (length?) in the spectrum window divided by the output rate to get the Hz per entry and found this code:

nyquistLength = length / 2;

for (int i = 0; i < nyquistLength - 1; ++i)
{
     float hz = i * (44100 * 0.5f) / (nyquistLength - 1);
}

an then I multiply that with my spectrum value e.g. spectrum[channel][length] ?
If that is so, can I use some if statements to get the frequency 400-800Hz.
Thanks!

nyquistLength refers to half the entries in the resulting array. It will be the window size divided by 2. Its a bit of a misleading name really.

You will want to divide the nyquist frequency (samplingrate /2) by half of the window size (ie 1024 fft length = 512 entries) to get the hz value per entry.

That means it should be along these lines:

nyquistRate = sampleRate / 2
numEntries = (numValues / 2)
hzPerEntry = nyquistRate / numEntries
for (count = 0; count < numEntries; count+)
{
    entrypower = spectrumData[channel][count] * hzPerEntry
    // pick the biggest power here or process the array to get a better result
    // (count+0.5) * hzPerEntry will be the frequency to display.
}

Otherwise the FFT dsp also has a way to get the dominant frequency from a channel:
FMOD_DSP_FFT_DOMINANT_FREQ
https://fmod.com/resources/documentation-api?page=content/generated/FMOD_DSP_FFT.html

Edit: I missed the part where you need to halve the number of values to match the nyquistLength, as the 2nd half is a mirror image and has the imaginary parts of the complex numbers.

1 Like

Hello Cameron,thanks for the answer! The values returned by freq are too small, the highest freq is 11.87. With the FMOD_DSP_FFT_DOMINANT_FREQ I get 3310, 2765 and so on as the peak frequency. Am I missing something?

I have updated the answer above.