Skip to content

Commit

Permalink
Fixes issue #147 (#160)
Browse files Browse the repository at this point in the history
Fixes

->Added error handling for PyAudio initialization.
->Consolidate GUI update functions.
->Add dynamic resizing of the graph canvas.

Co-authored-by: tkshsbcue <kumar.tanay397@gmail.com>
  • Loading branch information
tkshsbcue and tkshsbcue authored Jul 13, 2024
1 parent 1f56ec3 commit 6027a29
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 59 deletions.
34 changes: 19 additions & 15 deletions Home.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
[sg.Button("Spectrogram", **button_style, pad=(10, 10))],
[sg.Button("Intensity vs Frequency and Time", **button_style, pad=(10, 10))],
[sg.Button("Real-Time VU Meter", **button_style, pad=(10, 10))], # New button for Triangle Wave
]
]

# Layout for the main landing page
layout = [
Expand All @@ -40,6 +40,23 @@ def close_current_visualizer(process):
process.kill()
process.wait()

# Consolidated function to handle GUI updates
def handle_event(event, process):
# Mapping event to corresponding script names
script_mapping = {
"Amplitude-Frequency Visualizer": "Amplitude-Frequency-Visualizer.py",
"Waveform": "Waveform.py",
"Spectrogram": "Spectrogram.py",
"Intensity vs Frequency and Time": "Intensity-vs-Frequency-and-time.py",
"Real-Time VU Meter": "Real-Time VU Meter.py", # Added button for "Triangle Wave"
}

if event in script_mapping:
close_current_visualizer(process)
script_name = script_mapping[event]
return subprocess.Popen([sys.executable, script_name])
return process

# Main loop
current_visualizer_process = None

Expand All @@ -50,19 +67,6 @@ def close_current_visualizer(process):
close_current_visualizer(current_visualizer_process)
break

if event in ["Amplitude-Frequency Visualizer", "Waveform", "Spectrogram", "Intensity vs Frequency and Time","Real-Time VU Meter", "Sine Wave", "Square Wave", "Triangle Wave", "Sawtooth Wave"]:
close_current_visualizer(current_visualizer_process)

# Mapping event to corresponding script names
script_mapping = {
"Amplitude-Frequency Visualizer": "Amplitude-Frequency-Visualizer.py",
"Waveform": "Waveform.py",
"Spectrogram": "Spectrogram.py",
"Intensity vs Frequency and Time": "Intensity-vs-Frequency-and-time.py",
"Real-Time VU Meter": "Real-Time VU Meter.py", # Added button for "Triangle Wave"
}

script_name = script_mapping[event]
current_visualizer_process = subprocess.Popen([sys.executable, script_name])
current_visualizer_process = handle_event(event, current_visualizer_process)

window.close()
43 changes: 18 additions & 25 deletions Index.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,6 @@
import tkinter as tk
import subprocess

def run_spec():
subprocess.Popen(["python", "Spectogram.py"])

def run_wave():
subprocess.Popen(["python", "Waveform.py"])

def run_AvsF():
subprocess.Popen(["python", "Amplitude-Frequency-Visualizer.py"])

def run_IvsF():
subprocess.Popen(["python", "Intensity-vs-Frequency-and-time.py"])

def center_window(window, width, height):
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
Expand All @@ -22,14 +10,23 @@ def center_window(window, width, height):

window.geometry(f"{width}x{height}+{x_coordinate}+{y_coordinate}")

def create_button(frame, text, command, bg, fg, font, row, column):
button = tk.Button(frame, text=text, command=command, bg=bg, fg=fg, relief=tk.FLAT, font=font, bd=0)
button.config(highlightbackground=bg, highlightcolor=bg, highlightthickness=2, borderwidth=0, padx=20, pady=10)
button.grid(row=row, column=column, padx=10, pady=10, sticky="nsew")
button.bind("<Enter>", lambda e, b=button: b.config(bg="#444444")) # Change button color on hover
button.bind("<Leave>", lambda e, b=button: b.config(bg=bg)) # Restore button color on leave

def run_visualizer(script_name):
subprocess.Popen(["python", script_name])

root = tk.Tk()
root.title("Soundscape")
root.configure(bg="#1e1e1e") # Dark background color

button_bg = "#292929" # Dark gray
button_fg = "#FFFFFF" # White
button_font = ("Helvetica", 12) # Button font
button_radius = 10 # Button corner radius

window_width = 600
window_height = 400
Expand All @@ -40,21 +37,17 @@ def center_window(window, width, height):
button_frame = tk.Frame(root, bg="#1e1e1e") # Dark background color
button_frame.place(relx=0.5, rely=0.5, anchor="center")

# Define button texts and corresponding commands
# Define button texts and corresponding script names
buttons = [
("Spectogram", run_spec),
("Waveform", run_wave),
("Amplitude vs Frequency", run_AvsF),
("Intensity vs Frequency", run_IvsF)
("Spectogram", "Spectogram.py"),
("Waveform", "Waveform.py"),
("Amplitude vs Frequency", "Amplitude-Frequency-Visualizer.py"),
("Intensity vs Frequency", "Intensity-vs-Frequency-and-time.py")
]

# Create buttons in a matrix layout
for i, (text, command) in enumerate(buttons):
for i, (text, script) in enumerate(buttons):
row, column = divmod(i, 2) # 2 buttons per row
button = tk.Button(button_frame, text=text, command=command, bg=button_bg, fg=button_fg, relief=tk.FLAT, font=button_font, bd=0)
button.config(highlightbackground=button_bg, highlightcolor=button_bg, highlightthickness=2, borderwidth=0, padx=20, pady=10)
button.grid(row=row, column=column, padx=10, pady=10, sticky="nsew")
button.bind("<Enter>", lambda e, b=button: b.config(bg="#444444")) # Change button color on hover
button.bind("<Leave>", lambda e, b=button: b.config(bg=button_bg)) # Restore button color on leave
create_button(button_frame, text, lambda s=script: run_visualizer(s), button_bg, button_fg, button_font, row, column)

root.mainloop()
root.mainloop()
53 changes: 34 additions & 19 deletions Spectrogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
_VARS = {"stream": None, "audioData": np.array([])}
CHUNK = 1024
RATE = 44100
pAud = pyaudio.PyAudio()

# Check if audio input is available
# Initialize PyAudio
try:
pAud = pyaudio.PyAudio()
pAud.get_device_info_by_index(0)
except pyaudio.PyAudioError as e:
print(f"Error initializing PyAudio: {e}")
Expand All @@ -32,21 +32,32 @@ def callback(in_data, frame_count, time_info, status):
return (in_data, pyaudio.paContinue)

def listen():
_VARS["stream"] = pAud.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback,
)
_VARS["stream"].start_stream()
if pAud:
try:
_VARS["stream"] = pAud.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback,
)
_VARS["stream"].start_stream()
except Exception as e:
print(f"Error starting audio stream: {e}")
_VARS["stream"] = None
else:
print("PyAudio is not initialized.")

def stop():
if _VARS["stream"]:
_VARS["stream"].stop_stream()
_VARS["stream"].close()
_VARS["stream"] = None
try:
_VARS["stream"].stop_stream()
_VARS["stream"].close()
except Exception as e:
print(f"Error stopping audio stream: {e}")
finally:
_VARS["stream"] = None

class SpectrogramApp(App):
def build(self):
Expand Down Expand Up @@ -84,10 +95,13 @@ def build(self):

def on_listen(self, instance):
listen()
self.listen_button.disabled = True
self.stop_button.disabled = False
self.save_button.disabled = False
self.event = Clock.schedule_interval(self.update, 0.1)
if _VARS["stream"]:
self.listen_button.disabled = True
self.stop_button.disabled = False
self.save_button.disabled = False
self.event = Clock.schedule_interval(self.update, 0.1)
else:
print("Failed to start listening.")

def on_stop(self, instance):
stop()
Expand Down Expand Up @@ -117,7 +131,8 @@ def save(instance):

def on_exit(self, instance):
stop()
pAud.terminate()
if pAud:
pAud.terminate()
App.get_running_app().stop()

def save_figure(self, file_path):
Expand Down

0 comments on commit 6027a29

Please sign in to comment.