Skip to content

Commit 56c063c

Browse files
Add files via upload
0 parents  commit 56c063c

4 files changed

+383
-0
lines changed

Amplitude-Frequency-Visualizer.py

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import PySimpleGUI as sg
2+
import pyaudio
3+
import numpy as np
4+
import scipy.fft
5+
import matplotlib.pyplot as plt
6+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
7+
8+
""" RealTime Audio Frequency plot """
9+
10+
# VARS CONSTS:
11+
_VARS = {"window": False, "stream": False, "audioData": np.array([])}
12+
13+
# pysimpleGUI INIT:
14+
AppFont = "Any 16"
15+
sg.theme("DarkBlue3")
16+
layout = [
17+
[
18+
sg.Graph(
19+
canvas_size=(500, 500),
20+
graph_bottom_left=(-2, -2),
21+
graph_top_right=(102, 102),
22+
background_color="#809AB6",
23+
key="graph",
24+
)
25+
],
26+
[sg.ProgressBar(4000, orientation="h", size=(20, 20), key="-PROG-")],
27+
[
28+
sg.Button("Listen", font=AppFont),
29+
sg.Button("Stop", font=AppFont, disabled=True),
30+
sg.Button("Exit", font=AppFont),
31+
],
32+
]
33+
_VARS["window"] = sg.Window("Mic to frequency plot + Max Level", layout, finalize=True)
34+
35+
graph = _VARS["window"]["graph"]
36+
37+
# INIT vars:
38+
CHUNK = 1024 # Samples: 1024, 512, 256, 128
39+
RATE = 44100 # Equivalent to Human Hearing at 40 kHz
40+
INTERVAL = 1 # Sampling Interval in Seconds -> Interval to listen
41+
TIMEOUT = 10 # In ms for the event loop
42+
pAud = pyaudio.PyAudio()
43+
44+
# FUNCTIONS:
45+
46+
47+
# PySimpleGUI plots:
48+
def draw_figure(canvas, figure):
49+
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
50+
figure_canvas_agg.draw()
51+
figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
52+
return figure_canvas_agg
53+
54+
55+
# pyaudio stream:
56+
def stop():
57+
if _VARS["stream"]:
58+
_VARS["stream"].stop_stream()
59+
_VARS["stream"].close()
60+
_VARS["window"]["-PROG-"].update(0)
61+
_VARS["window"]["Stop"].Update(disabled=True)
62+
_VARS["window"]["Listen"].Update(disabled=False)
63+
64+
65+
# callback:
66+
def callback(in_data, frame_count, time_info, status):
67+
_VARS["audioData"] = np.frombuffer(in_data, dtype=np.int16)
68+
return (in_data, pyaudio.paContinue)
69+
70+
71+
def listen():
72+
_VARS["window"]["Stop"].Update(disabled=False)
73+
_VARS["window"]["Listen"].Update(disabled=True)
74+
_VARS["stream"] = pAud.open(
75+
format=pyaudio.paInt16,
76+
channels=1,
77+
rate=RATE,
78+
input=True,
79+
frames_per_buffer=CHUNK,
80+
stream_callback=callback,
81+
)
82+
_VARS["stream"].start_stream()
83+
84+
85+
# INIT:
86+
fig, ax = plt.subplots() # create a figure and an axis object
87+
fig_agg = draw_figure(graph.TKCanvas, fig) # draw the figure on the graph
88+
89+
# MAIN LOOP
90+
while True:
91+
event, values = _VARS["window"].read(timeout=TIMEOUT)
92+
if event == sg.WIN_CLOSED or event == "Exit":
93+
stop()
94+
pAud.terminate()
95+
break
96+
if event == "Listen":
97+
listen()
98+
if event == "Stop":
99+
stop()
100+
101+
# Along with the global audioData variable, this
102+
# bit updates the frequency plot
103+
104+
elif _VARS["audioData"].size != 0:
105+
# Update volume meter
106+
_VARS["window"]["-PROG-"].update(np.amax(_VARS["audioData"]))
107+
# Compute frequency spectrum
108+
yf = scipy.fft.fft(_VARS["audioData"]) # compute the discrete Fourier transform
109+
xf = np.linspace(0.0, RATE / 2, CHUNK // 2) # create the frequency axis
110+
# Plot frequency spectrum
111+
ax.clear() # clear the previous plot
112+
ax.plot(
113+
xf, 2.0 / CHUNK * np.abs(yf[: CHUNK // 2])
114+
) # plot the frequency spectrum as a line graph
115+
ax.set_ylabel("Amplitude") # set the y-axis label
116+
ax.set_xlabel("Frequency [Hz]") # set the x-axis label
117+
fig_agg.draw() # redraw the figure

Spectogram.py

+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import PySimpleGUI as sg
2+
import pyaudio
3+
import numpy as np
4+
import scipy.signal
5+
import matplotlib.pyplot as plt
6+
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
7+
8+
""" RealTime Audio Time-Frequency plot """
9+
10+
# VARS CONSTS:
11+
_VARS = {"window": False, "stream": False, "audioData": np.array([])}
12+
13+
# pysimpleGUI INIT:
14+
AppFont = "Any 16"
15+
sg.theme("DarkBlue3")
16+
layout = [
17+
[
18+
sg.Graph(
19+
canvas_size=(500, 500),
20+
graph_bottom_left=(-2, -2),
21+
graph_top_right=(102, 102),
22+
background_color="#809AB6",
23+
key="graph",
24+
)
25+
],
26+
[sg.ProgressBar(4000, orientation="h", size=(20, 20), key="-PROG-")],
27+
[
28+
sg.Button("Listen", font=AppFont),
29+
sg.Button("Stop", font=AppFont, disabled=True),
30+
sg.Button("Exit", font=AppFont),
31+
],
32+
]
33+
_VARS["window"] = sg.Window(
34+
"Mic to time-frequency plot + Max Level", layout, finalize=True
35+
)
36+
37+
graph = _VARS["window"]["graph"]
38+
39+
# INIT vars:
40+
CHUNK = 1024 # Samples: 1024, 512, 256, 128
41+
RATE = 44100 # Equivalent to Human Hearing at 40 kHz
42+
INTERVAL = 1 # Sampling Interval in Seconds -> Interval to listen
43+
TIMEOUT = 10 # In ms for the event loop
44+
pAud = pyaudio.PyAudio()
45+
46+
# FUNCTIONS:
47+
48+
49+
# PySimpleGUI plots:
50+
def draw_figure(canvas, figure):
51+
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
52+
figure_canvas_agg.draw()
53+
figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1)
54+
return figure_canvas_agg
55+
56+
57+
# pyaudio stream:
58+
def stop():
59+
if _VARS["stream"]:
60+
_VARS["stream"].stop_stream()
61+
_VARS["stream"].close()
62+
_VARS["window"]["-PROG-"].update(0)
63+
_VARS["window"]["Stop"].Update(disabled=True)
64+
_VARS["window"]["Listen"].Update(disabled=False)
65+
66+
67+
# callback:
68+
def callback(in_data, frame_count, time_info, status):
69+
_VARS["audioData"] = np.frombuffer(in_data, dtype=np.int16)
70+
return (in_data, pyaudio.paContinue)
71+
72+
73+
def listen():
74+
_VARS["window"]["Stop"].Update(disabled=False)
75+
_VARS["window"]["Listen"].Update(disabled=True)
76+
_VARS["stream"] = pAud.open(
77+
format=pyaudio.paInt16,
78+
channels=1,
79+
rate=RATE,
80+
input=True,
81+
frames_per_buffer=CHUNK,
82+
stream_callback=callback,
83+
)
84+
_VARS["stream"].start_stream()
85+
86+
87+
# INIT:
88+
fig, ax = plt.subplots() # create a figure and an axis object
89+
fig_agg = draw_figure(graph.TKCanvas, fig) # draw the figure on the graph
90+
91+
# MAIN LOOP
92+
while True:
93+
event, values = _VARS["window"].read(timeout=TIMEOUT)
94+
if event == sg.WIN_CLOSED or event == "Exit":
95+
stop()
96+
pAud.terminate()
97+
break
98+
if event == "Listen":
99+
listen()
100+
if event == "Stop":
101+
stop()
102+
103+
# Along with the global audioData variable, this
104+
# bit updates the time-frequency plot
105+
106+
elif _VARS["audioData"].size != 0:
107+
# Update volume meter
108+
_VARS["window"]["-PROG-"].update(np.amax(_VARS["audioData"]))
109+
# Compute time-frequency spectrum
110+
f, Pxx = scipy.signal.periodogram(
111+
_VARS["audioData"], fs=RATE
112+
) # compute the power spectral density
113+
t = np.arange(len(_VARS["audioData"])) / RATE # create the time axis
114+
# Plot time-frequency spectrum
115+
ax.clear() # clear the previous plot
116+
# Resize the frequency array to match the length of the time array
117+
f = np.resize(f, t.shape)
118+
# Plot the time-frequency spectrum as a line graph
119+
ax.plot(t, f)
120+
121+
ax.set_ylabel("Frequency [Hz]") # set the y-axis label
122+
ax.set_xlabel("Time [sec]") # set the x-axis label
123+
fig_agg.draw() # redraw the figure

Waveform.py

+121
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import PySimpleGUI as sg
2+
import pyaudio
3+
import numpy as np
4+
5+
""" RealTime Audio Waveform plot """
6+
7+
# VARS CONSTS:
8+
_VARS = {"window": False, "stream": False, "audioData": np.array([])}
9+
10+
# pysimpleGUI INIT:
11+
AppFont = "Any 16"
12+
sg.theme("DarkBlue3")
13+
layout = [
14+
[
15+
sg.Graph(
16+
canvas_size=(500, 500),
17+
graph_bottom_left=(-2, -2),
18+
graph_top_right=(102, 102),
19+
background_color="#809AB6",
20+
key="graph",
21+
)
22+
],
23+
[sg.ProgressBar(4000, orientation="h", size=(20, 20), key="-PROG-")],
24+
[
25+
sg.Button("Listen", font=AppFont),
26+
sg.Button("Stop", font=AppFont, disabled=True),
27+
sg.Button("Exit", font=AppFont),
28+
],
29+
]
30+
_VARS["window"] = sg.Window("Mic to waveform plot + Max Level", layout, finalize=True)
31+
32+
graph = _VARS["window"]["graph"]
33+
34+
# INIT vars:
35+
CHUNK = 1024 # Samples: 1024, 512, 256, 128
36+
RATE = 44100 # Equivalent to Human Hearing at 40 kHz
37+
INTERVAL = 1 # Sampling Interval in Seconds -> Interval to listen
38+
TIMEOUT = 10 # In ms for the event loop
39+
pAud = pyaudio.PyAudio()
40+
41+
# FUNCTIONS:
42+
43+
44+
# PySimpleGUI plots:
45+
def drawAxis(dataRangeMin=0, dataRangeMax=100):
46+
# Y Axis
47+
graph.DrawLine((0, 50), (100, 50))
48+
# X Axis
49+
graph.DrawLine((0, dataRangeMin), (0, dataRangeMax))
50+
51+
52+
# pyaudio stream:
53+
def stop():
54+
if _VARS["stream"]:
55+
_VARS["stream"].stop_stream()
56+
_VARS["stream"].close()
57+
_VARS["window"]["-PROG-"].update(0)
58+
_VARS["window"]["Stop"].Update(disabled=True)
59+
_VARS["window"]["Listen"].Update(disabled=False)
60+
61+
62+
# callback:
63+
def callback(in_data, frame_count, time_info, status):
64+
_VARS["audioData"] = np.frombuffer(in_data, dtype=np.int16)
65+
return (in_data, pyaudio.paContinue)
66+
67+
68+
def listen():
69+
_VARS["window"]["Stop"].Update(disabled=False)
70+
_VARS["window"]["Listen"].Update(disabled=True)
71+
_VARS["stream"] = pAud.open(
72+
format=pyaudio.paInt16,
73+
channels=1,
74+
rate=RATE,
75+
input=True,
76+
frames_per_buffer=CHUNK,
77+
stream_callback=callback,
78+
)
79+
_VARS["stream"].start_stream()
80+
81+
82+
# INIT:
83+
drawAxis()
84+
85+
86+
# MAIN LOOP
87+
while True:
88+
event, values = _VARS["window"].read(timeout=TIMEOUT)
89+
if event == sg.WIN_CLOSED or event == "Exit":
90+
stop()
91+
pAud.terminate()
92+
break
93+
if event == "Listen":
94+
listen()
95+
if event == "Stop":
96+
stop()
97+
98+
# Along with the global audioData variable, this
99+
# bit updates the waveform plot
100+
101+
elif _VARS["audioData"].size != 0:
102+
# Uodate volumne meter
103+
_VARS["window"]["-PROG-"].update(np.amax(_VARS["audioData"]))
104+
# Redraw plot
105+
graph.erase()
106+
drawAxis()
107+
108+
# Here we go through the points in the audioData object and draw them
109+
# Note that we are rescaling ( dividing by 100 ) and centering (+50)
110+
# try different values to get a feel for what they do.
111+
112+
for x in range(CHUNK):
113+
graph.DrawCircle(
114+
(x, (_VARS["audioData"][x] / 100) + 50),
115+
0.4,
116+
line_color="blue",
117+
fill_color="blue",
118+
)
119+
120+
121+
_VARS["window"].close()

requirements.txt

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
cffi==1.16.0
2+
contourpy==1.1.1
3+
cycler==0.12.1
4+
fonttools==4.47.2
5+
importlib-resources==6.1.1
6+
kiwisolver==1.4.5
7+
matplotlib==3.7.4
8+
mkl-fft @ file:///C:/b/abs_19i1y8ykas/croot/mkl_fft_1695058226480/work
9+
mkl-random @ file:///C:/b/abs_edwkj1_o69/croot/mkl_random_1695059866750/work
10+
mkl-service==2.4.0
11+
numpy @ file:///C:/Users/dev-admin/mkl/numpy_and_numpy_base_1682982345978/work
12+
packaging==23.2
13+
pillow==10.2.0
14+
PyAudio==0.2.14
15+
pycparser==2.21
16+
pyparsing==3.1.1
17+
PySimpleGUI==4.60.5
18+
python-dateutil==2.8.2
19+
scipy==1.10.1
20+
six==1.16.0
21+
sounddevice==0.4.6
22+
zipp==3.17.0

0 commit comments

Comments
 (0)