From 353fef4f840873e555dac520731465661193a685 Mon Sep 17 00:00:00 2001 From: deanlee Date: Sat, 27 Jul 2024 18:23:56 +0800 Subject: [PATCH] Optimize Processing with Real FFT and Cached Hanning Window --- system/micd.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/system/micd.py b/system/micd.py index af1aa3136063a7..41c29c7adad617 100755 --- a/system/micd.py +++ b/system/micd.py @@ -18,11 +18,16 @@ def get_a_weighting_filter(): # Calculate the A-weighting filter # https://en.wikipedia.org/wiki/A-weighting - freqs = np.fft.fftfreq(FFT_SAMPLES, d=1 / SAMPLE_RATE) + freqs = np.fft.rfftfreq(FFT_SAMPLES, d=1 / SAMPLE_RATE) A = 12194 ** 2 * freqs ** 4 / ((freqs ** 2 + 20.6 ** 2) * (freqs ** 2 + 12194 ** 2) * np.sqrt((freqs ** 2 + 107.7 ** 2) * (freqs ** 2 + 737.9 ** 2))) return A / np.max(A) +@cache +def get_hanning_window(size): + return np.hanning(size) + + def calculate_spl(measurements): # https://www.engineeringtoolbox.com/sound-pressure-d_711.html sound_pressure = np.sqrt(np.mean(measurements ** 2)) # RMS of amplitudes @@ -35,10 +40,12 @@ def calculate_spl(measurements): def apply_a_weighting(measurements: np.ndarray) -> np.ndarray: # Generate a Hanning window of the same length as the audio measurements - measurements_windowed = measurements * np.hanning(len(measurements)) - + hanning_windowed_measurements = measurements * get_hanning_window(len(measurements)) # Apply the A-weighting filter to the signal - return np.abs(np.fft.ifft(np.fft.fft(measurements_windowed) * get_a_weighting_filter())) + weighted_fft = np.fft.rfft(hanning_windowed_measurements) * get_a_weighting_filter() + weighted_measurements = np.fft.irfft(weighted_fft) + + return np.abs(weighted_measurements) class Mic: