I am fairly new to python and signal processing and I was given a task to record audio for 'x' seconds and then find the peak frequency in the audio file.
So far I have successfully implemented the recording part (records as a .wav file, sample rate = 44.1 kHz) but I am unable to correctly find and output the peak frequency in that file.
The goal of this task is that if a frequency above a certain threshold is found, other actions will take place. Could anyone please assist me on how to find the peak frequency.
So far I have attempted this using the scipy fft package and some pieces of code taken from research.
from scipy import signal
from scipy.io import wavfile
from scipy.fftpack import fft, ifft,fftfreq
import matplotlib.pyplot as plt
import wave
import numpy as np
import sys
import struct
frate,data = wavfile.read('output.wav')
print(frate)
w = np.fft.fft(data)
freqs = np.fft.fftfreq(len(w))
# Find the peak in the coefficients
idx = np.argmax(np.abs(w))
print(idx)
freq = freqs[idx]
freq_in_hertz = abs(freq * frate)
print(freq_in_hertz)
print("HZ")
When audio is recorded, the above code sometimes works but however, an incorrect peak frequency is detected (for example I record something that I know has frequencies of 10kHz but it says peak frequency detected is 6kHz)
Other times when I record audio and try to find the peak frequency, i get the following error message: Exception has occurred: IndexError index 547388 is out of bounds for axis 0 with size 480000 File "C:\Users\aviso\Documents\VS Code Projects\FinalDesign\HighFreqTest.py", line 22, in freq = freqs[idx]