From 62ceacf10980ef96b1a227d76cdf3e7db82fd4de Mon Sep 17 00:00:00 2001 From: Anthony Wang Date: Mon, 3 Oct 2022 13:56:46 -0400 Subject: Add mic to beeper script --- mic.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 mic.py diff --git a/mic.py b/mic.py new file mode 100644 index 0000000..9b518f3 --- /dev/null +++ b/mic.py @@ -0,0 +1,40 @@ +import numpy as np +import pyaudio +from requests import get + +audio = pyaudio.PyAudio() +stream = audio.open( + format = pyaudio.paInt16, + channels = 1, + rate=44100, + input=True +) + +# https://stackoverflow.com/questions/45908268/how-to-know-the-frequency-of-audio-from-microphone +# https://stackoverflow.com/questions/3694918/how-to-extract-frequency-associated-with-fft-values-in-pytho +curfreq = 0 +stop = False + +while True: + chunk = stream.read(2048) + w = np.fft.fft(list(chunk))[10:100] + f = np.fft.fftfreq(4196) + i = 10+np.argmax(np.abs(w)) + mag = abs(w[i-10]) + freq = abs(2 * f[i] * 44100) + + if mag > 50000 and curfreq == 0: + # Detected mic input + # Start new freq + stop = False + curfreq = freq + print('Starting', curfreq) + get('http://10.242.6.228:5000/startfreq/' + str(curfreq)) + elif mag <= 50000 or abs(curfreq-freq) > 20: + if stop and curfreq != 0: + print('Stopping', curfreq) + get('http://10.242.6.228:5000/stopfreq/' + str(curfreq)) + curfreq = 0 + else: + # Stop next round + stop = True -- cgit v1.2.3-70-g09d2