-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrealtime_audio_visualization.py
42 lines (32 loc) · 1.24 KB
/
realtime_audio_visualization.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
import pyaudio
import wave
import sys
CHUNK = 1024
np.set_printoptions(suppress=True) # don't use scientific notation
CHUNK = 4096 # number of data points to read at a time
RATE = 44100 # time resolution of the recording device (Hz)
p=pyaudio.PyAudio() # start the PyAudio class
stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True,
frames_per_buffer=CHUNK) #uses default input device
# create a numpy array holding a single read of audio data
for i in range(300): #to it a few times just to see
data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
data = data * np.hanning(len(data)) # smooth the FFT by windowing data
fft = abs(np.fft.fft(data).real)
fft = fft[:int(len(fft)/2)] # keep only first half
freq = np.fft.fftfreq(CHUNK,1.0/RATE)
freq = freq[:int(len(freq)/2)] # keep only first half
freqPeak = freq[np.where(fft==np.max(fft))[0][0]]+1
print("peak frequency: %d Hz"%freqPeak)
# uncomment this if you want to see what the freq vs FFT looks like
plt.plot(freq,fft)
plt.axis([0,4000,None,None])
plt.show()
plt.close()
# close the stream gracefully
stream.stop_stream()
stream.close()
p.terminate()