Details | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
6 | daniel-mar | 1 | #!/usr/bin/env python3 |
2 | |||
3 | import pyaudio |
||
4 | import numpy as np |
||
5 | |||
6 | CHUNK = 2*4096 # number of data points to read at a time |
||
7 | RATE = 48000 # time resolution of the recording device (Hz) |
||
8 | DEVICE = 1 # Webcam |
||
9 | |||
10 | p = pyaudio.PyAudio() |
||
11 | |||
12 | stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True, input_device_index=DEVICE, |
||
13 | frames_per_buffer=CHUNK) |
||
14 | |||
15 | while True: |
||
16 | indata = np.fromstring(stream.read(CHUNK),dtype=np.int16) |
||
17 | |||
18 | # Take the fft and square each value |
||
19 | fftData=abs(np.fft.rfft(indata))**2 |
||
20 | # find the maximum |
||
21 | which = fftData[1:].argmax() + 1 |
||
22 | # use quadratic interpolation around the max |
||
23 | if which != len(fftData)-1: |
||
24 | y0,y1,y2 = np.log(fftData[which-1:which+2:]) |
||
25 | x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0) |
||
26 | # find the frequency and output it |
||
27 | thefreq = (which+x1)*RATE/CHUNK |
||
28 | print("The freq is %f Hz." % (thefreq)) |
||
29 | else: |
||
30 | thefreq = which*RATE/CHUNK |
||
31 | print("The freq is %f Hz." % (thefreq)) |
||
32 | |||
33 | stream.close() |
||
34 | p.terminate() |