Search code examples
pythonnumpyfft

Load an audio file and find the frequency


I have a following code:

rate, data = wav.read('C.wav')
Fourier = abs(fftpk.fft(data))

max = np.argmax(Fourier, axis=None, out=None)
print(max) # get 787


freq = fftpk.fftfreq(len(Fourier), (1.0/rate))

plt.plot(freq[range(len(Fourier)//2)], Fourier[range(len(Fourier)//2)])
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude')
plt.show()

I want this program to give me the frequency in Hz with the highest amplitude, but instead of getting value around 260, I get 787. I do not know what the problem is.

Plot of the file:

Plot of the file


Solution

  • np.argmax gives you the index of the maximum element in the Fourier frequency, not the actual frequency. The relation to obtain the frequency from the index is frequency = index*rate/len(Fourier). So, applying this in your case should give you the desired frequency:

    max = np.argmax(Fourier, axis=None, out=None)
    print(max) # get 787
    maxfreq = max*rate/len(Fourier) # should give ~260