-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_spectrum.py
68 lines (49 loc) · 1.63 KB
/
4_spectrum.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Learning to visualize audio
# Mr. Poznanski == Poz - nan - ski == Pause - NaN - Ski
# Now, we are going to draw the waveform as a graph
import numpy as np
import PySimpleGUI as sg
import pyaudio
sg.theme("BluePurple")
FFT_BINS = 200
layout = [
[sg.Graph(canvas_size=(500,300),
graph_bottom_left=(0, 0),
graph_top_right=(1,1), key="graph")],
[sg.Graph(canvas_size=(500, 300),
graph_bottom_left=(0, 0),
graph_top_right=(FFT_BINS, 1), key="bars")],
]
window = sg.Window("Visualization", layout, finalize=True)
graph = window["graph"]
bars = window["bars"]
# Setup the microphone
RATE = 44100 # (sampling rate) number of frames per second
CHANNELS = 1
CHUNK = 1000 # signal is split into CHUNK number of frames
FORMAT = pyaudio.paInt16
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
while True:
event, values = window.read(timeout=10)
if event == sg.WIN_CLOSED:
break
raw = stream.read(CHUNK, exception_on_overflow=False)
data = np.frombuffer(raw, dtype=np.int16)
data = data.astype(np.float32) / 65535.0
graph.erase()
points = []
for x, y in enumerate(data):
points.append((x / CHUNK, y * 2 + 0.5))
graph.draw_lines(points, color="red", width=1)
fft = np.fft.rfft(data, n=FFT_BINS)
fft = np.abs(fft) * 0.2
bars.erase()
for i in range(1, FFT_BINS // 2):
bars.draw_rectangle((2 * i, 0.0), (2 * (i+1), fft[i]), fill_color="green", line_width=0)
stream.close()
window.close()