My goal is to write a Python program that records sound from a microphone and prints the volume of a specific frequency range (using a bandpass filter) continuously.
Below is the code which I currently have. I googled for hours to find out more about this topic or code samples, but I didn't find any useful information (that I can understand) or fitting example codes. Unfortunately, my knowledge in FFT is very limited.
Currently, I have two problems:
Problem 1: The bandpass filter does not work. I set it to 300Hz..500Hz, but it doesn't really filter anything. As an example, I have added a code that displays the main frequency of the signal, so I can see if the filter works (for testing, I play sounds with a frequency generator app). The frequency detection works perfectly, but the signal is not filtered to 300..500Hz.
Problem 2: How can I determine the volume? My idea was to use noiselevel = np.average(fftData) to find out the average volume over all frequencies in the fftData array. But it does not work: The output seems arbitary and does not react to loud sounds played into the microphone.
I'd be grateful for any help. Thank you very much!
#!/usr/bin/env python3
import pyaudio
import numpy as np
from scipy.signal import butter, sosfilt
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
sos = butter(order, [low, high], analog=False, btype='band', output='sos')
return sos
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
sos = butter_bandpass(lowcut, highcut, fs, order=order)
y = sosfilt(sos, data)
return y
CHUNK = 2*4096 # number of data points to read at a time
RATE = 48000 # time resolution of the recording device (Hz)
DEVICE = 0 # default
p = pyaudio.PyAudio()
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True, input_device_index=DEVICE,
frames_per_buffer=CHUNK)
while True:
indata = np.fromstring(stream.read(CHUNK),dtype=np.int16)
# Remove everything except 300Hz..500Hz
# TODO: does not work
#indata = butter_bandpass_filter(indata, 300, 500, RATE, order=5)
# Take the fft and square each value
fftData=abs(np.fft.rfft(indata))**2
# TODO: find out volume
noiselevel = np.average(fftData)
print("Volume of 300Hz..500Hz: %f" % (noiselevel))
# JUST FOR TESTING: Find out frequency (to see if band pass works correctly)
# find the maximum
which = fftData[1:].argmax() + 1
# use quadratic interpolation around the max
if which != len(fftData)-1:
y0,y1,y2 = np.log(fftData[which-1:which+2:])
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
# find the frequency and output it
thefreq = (which+x1)*RATE/CHUNK
print("Frequency: %f Hz." % (thefreq))
else:
thefreq = which*RATE/CHUNK
print("Frequency: %f Hz." % (thefreq))
# END <JUST FOR TESTING>
stream.close()
p.terminate()
UPDATE: Here is my second try, without filters:
while True:
indata = np.fromstring(stream.read(CHUNK),dtype=np.int16)
# Get volume of 440 Hz
fftData=np.fft.rfft(indata)
freqs = np.fft.rfftfreq(fftData.size)
idx = (np.abs(freqs-440)).argmin()
volume = np.abs(fftData[idx]) # does not work
print(volume)