-
Notifications
You must be signed in to change notification settings - Fork 83
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Updated Spectogram.py #82
Open
Shubhanshu-356
wants to merge
7
commits into
Soumya-Kushwaha:main
Choose a base branch
from
Shubhanshu-356:gui-performance-enhancement
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
dd46869
Updated Spectogram.py
Shubhanshu-356 e0011b9
Merge branch 'main' into gui-performance-enhancement
Shubhanshu-356 c11cad4
Merge branch 'main' into gui-performance-enhancement
Shubhanshu-356 78647af
Update Spectogram.py
Shubhanshu-356 472c6a6
Merge branch 'main' into gui-performance-enhancement
Soumya-Kushwaha 5ce1673
Merge branch 'main' into gui-performance-enhancement
Shubhanshu-356 5661e41
Update Spectogram.py
Shubhanshu-356 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,16 +4,26 @@ | |
import scipy.signal | ||
import matplotlib.pyplot as plt | ||
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg | ||
gui-performance-enhancement | ||
import threading | ||
import queue | ||
import subprocess | ||
|
||
|
||
main | ||
|
||
""" RealTime Audio Spectrogram plot """ | ||
# Global variables | ||
_VARS = {"window": None, "stream": None, "audioData": np.array([])} | ||
audio_buffer = queue.Queue(maxsize=10) # Buffer for audio data | ||
stop_event = threading.Event() # Event to signal stopping of the audio stream | ||
|
||
gui-performance-enhancement | ||
# PySimpleGUI initialization | ||
# VARS CONSTS: | ||
_VARS = {"window": False, "stream": False, "audioData": np.array([]), "current_visualizer_process": None} | ||
|
||
# pysimpleGUI INIT: | ||
main | ||
AppFont = "Any 16" | ||
sg.theme("DarkBlue3") | ||
|
||
|
@@ -40,49 +50,44 @@ | |
], | ||
] | ||
_VARS["window"] = sg.Window("Mic to spectrogram plot + Max Level", layout, finalize=True) | ||
gui-performance-enhancement | ||
graph = _VARS["window"]["graph"] | ||
main | ||
|
||
# INIT vars: | ||
CHUNK = 1024 # Samples: 1024, 512, 256, 128 | ||
RATE = 44100 # Equivalent to Human Hearing at 40 kHz | ||
INTERVAL = 1 # Sampling Interval in Seconds -> Interval to listen | ||
TIMEOUT = 10 # In ms for the event loop | ||
# PyAudio initialization | ||
pAud = pyaudio.PyAudio() | ||
CHUNK = 1024 | ||
RATE = 44100 | ||
INTERVAL = 1 | ||
TIMEOUT = 100 # Adjusted timeout value | ||
|
||
try: | ||
pAud.get_device_info_by_index(0) | ||
except pyaudio.CoreError as e: | ||
print(f"Error initializing PyAudio: {e}") | ||
pAud = None | ||
# FUNCTIONS: | ||
|
||
|
||
# PySimpleGUI plots: | ||
def draw_figure(canvas, figure): | ||
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas) | ||
figure_canvas_agg.draw() | ||
figure_canvas_agg.get_tk_widget().pack(side="top", fill="both", expand=1) | ||
return figure_canvas_agg | ||
|
||
|
||
# pyaudio stream: | ||
def stop(): | ||
if _VARS["stream"]: | ||
if _VARS["stream"] is not None and _VARS["stream"].is_active(): | ||
stop_event.set() # Signal the audio processing thread to stop | ||
_VARS["stream"].stop_stream() | ||
_VARS["stream"].close() | ||
_VARS["stream"] = None | ||
_VARS["window"]["-PROG-"].update(0) | ||
gui-performance-enhancement | ||
_VARS["window"]["Stop"].update(disabled=True) | ||
_VARS["window"]["Listen"].update(disabled=False) | ||
stop_event.clear() # Reset the event for the next use | ||
|
||
|
||
_VARS["window"]["Stop"].Update(disabled=True) | ||
_VARS["window"]["Listen"].Update(disabled=False) | ||
|
||
# callback: | ||
main | ||
def callback(in_data, frame_count, time_info, status): | ||
_VARS["audioData"] = np.frombuffer(in_data, dtype=np.int16) | ||
if stop_event.is_set(): | ||
return (in_data, pyaudio.paComplete) | ||
audio_buffer.put(np.frombuffer(in_data, dtype=np.int16)) | ||
return (in_data, pyaudio.paContinue) | ||
|
||
def listen(): | ||
_VARS["window"]["Stop"].Update(disabled=False) | ||
_VARS["window"]["Listen"].Update(disabled=True) | ||
_VARS["window"]["Stop"].update(disabled=False) | ||
_VARS["window"]["Listen"].update(disabled=True) | ||
_VARS["stream"] = pAud.open( | ||
format=pyaudio.paInt16, | ||
channels=1, | ||
|
@@ -93,7 +98,50 @@ def listen(): | |
) | ||
_VARS["stream"].start_stream() | ||
|
||
def close_current_visualizer(): | ||
gui-performance-enhancement | ||
def audio_processing(ax, fig_agg): | ||
while not stop_event.is_set(): | ||
try: | ||
audio_data = audio_buffer.get(timeout=1) | ||
if audio_data.size != 0: | ||
_VARS["window"]["-PROG-"].update(np.amax(audio_data)) | ||
f, t, Sxx = scipy.signal.spectrogram(audio_data, fs=RATE) | ||
ax.clear() | ||
ax.pcolormesh(t, f, Sxx, shading="gouraud") | ||
ax.set_ylabel("Frequency [Hz]") | ||
ax.set_xlabel("Time [sec]") | ||
fig_agg.draw() | ||
except queue.Empty: | ||
continue | ||
|
||
def main(): | ||
# Initialization | ||
fig, ax = plt.subplots() | ||
fig_agg = FigureCanvasTkAgg(fig, _VARS["window"]["graph"].TKCanvas) | ||
fig_agg.draw() | ||
fig_agg.get_tk_widget().pack(side="top", fill="both", expand=1) | ||
|
||
# Multithreading for audio processing | ||
audio_thread = threading.Thread(target=audio_processing, args=(ax, fig_agg)) | ||
audio_thread.daemon = True | ||
audio_thread.start() | ||
|
||
# Event loop | ||
while True: | ||
event, values = _VARS["window"].read(timeout=TIMEOUT) | ||
if event == sg.WINDOW_CLOSED or event == "Exit": | ||
stop() | ||
pAud.terminate() | ||
break | ||
elif event == "Listen": | ||
listen() | ||
elif event == "Stop": | ||
stop() | ||
|
||
if __name__ == "__main__": | ||
main() | ||
|
||
def close_current_visualizer(): | ||
if _VARS["current_visualizer_process"] and _VARS["current_visualizer_process"].poll() is None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. block of code here is missing indentation |
||
_VARS["current_visualizer_process"].kill() | ||
|
||
|
@@ -154,3 +202,4 @@ def close_current_visualizer(): | |
ax.set_ylabel("Frequency [Hz]") # set the y-axis label | ||
ax.set_xlabel("Time [sec]") # set the x-axis label | ||
fig_agg.draw() # redraw the figure | ||
main |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could you remove branch names mentioned across the file for "main" and "gui-performance-enhancement"
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Means you are saying that I have to remove the branch name
Is it correct I am saying. What is the problem occuring by your side when you are merging. Can you please tell me
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, remove the branch names in the code file. I believe it might've occurred while solving a merge conflict
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok I will do thanks for the info
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you please check it now for merging
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I still see those!