0

How can I detect a whistle?

I would like the code to simply print a message once a frequency between 1000Hz and 2000Hz is heard through the microphone.

i.e.if frequency in range(1000, 2000) and amplitude >= 30: print("Hello World")

import pyaudio
import numpy
import math
import matplotlib.pyplot as plt
import matplotlib.animation


RATE = 44100
BUFFER = 882

p = pyaudio.PyAudio()

stream = p.open(
    format = pyaudio.paFloat32,
    channels = 1,
    rate = RATE,
    input = True,
    output = False,
    frames_per_buffer = BUFFER
)

fig = plt.figure()
line1 = plt.plot([],[])[0]
line2 = plt.plot([],[])[0]

r = range(0,int(RATE/2+1),int(RATE/BUFFER))
l = len(r)

def init_line():
        line1.set_data(r, [-1000]*l)
        line2.set_data(r, [-1000]*l)
        return (line1,line2,)

def update_line(i):
    try:
        data = numpy.fft.rfft(numpy.fromstring(
            stream.read(BUFFER), dtype=numpy.float32)
        )
    except IOError:
        pass
    data = numpy.log10(numpy.sqrt(
        numpy.real(data)**2+numpy.imag(data)**2) / BUFFER) * 10
    ####DATA IS DB
    print(data)
    line1.set_data(r, data)
    line2.set_data(numpy.maximum(line1.get_data(), line2.get_data()))
    return (line1,line2,)

plt.xlim(0, RATE/2+1)
plt.ylim(-60, 0)
plt.xlabel('Frequency')
plt.ylabel('dB')
plt.title('Spectrometer')
plt.grid()

line_ani = matplotlib.animation.FuncAnimation(fig, update_line, init_func=init_line, interval=0, blit=True)
plt.show()

In this FFT code I copied, I found that the variable data was the the amplitude - db. From this, I would need to find if there is a considerable increase in volume from 1000Hz to 2000Hz, which is the frequency range of most whistles.

bob ross
  • 1
  • 1
  • 1
    what have you tried so far? – raven May 10 '19 at 09:26
  • I have tried multiple FFT codes which worked and displayed the frequency graph/spectrum but I couldn't understand the values that were being used in it. I have also found out about the Goertzel algorithm... all of which I didn't understand as we have never covered anything of the sort in math or computer science (I am an IG student...). – bob ross May 10 '19 at 09:30
  • 1
    I meant what have you tried in code. Post some code, otherwise this question would be out of topic. – raven May 10 '19 at 09:39
  • carefully read this post and the one linked to which give context on how to make sense of the result of a fft call https://stackoverflow.com/questions/55430065/how-to-calculate-the-energy-per-bin-in-a-dft/55431279#55431279 – Scott Stensland May 10 '19 at 12:00

0 Answers0