Skip to content
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

Icons added for every visualizers and for mainLanding page #143

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 65 additions & 61 deletions Amplitude-Frequency-Visualizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,26 @@
import scipy.fft
import matplotlib.pyplot as plt
import subprocess
import traceback

# VARS CONSTS:

_VARS = {
"window": False,
"stream": False,
"audioData": np.array([]),
"audioBuffer": np.array([]),
"current_visualizer_process": None,
}

# PySimpleGUI INIT:
_VARS = {"window": False, "stream": False, "audioData": np.array([]), "audioBuffer": np.array([]),"current_visualizer_process": None}

# pysimpleGUI INIT:
AppFont = "Helvetica"
sg.theme("DarkBlue3")

menu_layout = [
['Run Visualizers', ['Amplitude-Frequency-Visualizer', 'Waveform', 'Spectogram', 'Intensity-vs-Frequency-and-time']],

['Run Visualizers', ['Amplitude-Frequency-Visualizer', 'Waveform', 'Spectogram','Intensity-vs-Frequency-and-time']],
]


layout = [
[sg.Menu(menu_layout)],
[ sg.Menu(menu_layout)],
[

sg.Graph(
canvas_size=(600, 600),
graph_bottom_left=(-2, -2),
Expand All @@ -38,18 +35,18 @@
tooltip="Frequency graph" # Tooltip added
)
],
[sg.Text("Progress:", text_color='white', font=('Helvetica', 15, 'bold')), sg.ProgressBar(4000, orientation="h", size=(20, 20), key="-PROG-")],
[sg.Text("Progress:", text_color='white', font=('Helvetica', 15, 'bold')), sg.ProgressBar(4000, orientation="h", size=(20, 20), key="-PROG-")],
[
sg.Button("Listen", font=AppFont, tooltip="Start listening"),
sg.Button("Pause", font=AppFont, disabled=True, tooltip="Pause listening"),
sg.Button("Pause", font=AppFont, disabled=True, tooltip="Pause listening"),
sg.Button("Resume", font=AppFont, disabled=True, tooltip="Resume listening"),
sg.Button("Stop", font=AppFont, disabled=True, tooltip="Stop listening"),
sg.Button("Save", font=AppFont, disabled=True, tooltip="Save the plot"),
sg.Button("Exit", font=AppFont, tooltip="Exit the application"),
sg.Button("Stop", font=AppFont, disabled=True, tooltip="Stop listening"),
sg.Button("Save", font=AppFont, disabled=True, tooltip="Save the plot"),
sg.Button("Exit", font=AppFont, tooltip="Exit the application"),
],
]

_VARS["window"] = sg.Window("Mic to frequency plot + Max Level", layout, finalize=True)
_VARS["window"] = sg.Window("Mic to frequency plot + Max Level", layout,icon="icons/amp-freq.ico", finalize=True)
graph = _VARS["window"]["graph"]

# INIT vars:
Expand All @@ -75,15 +72,16 @@ def stop():
_VARS["window"]["-PROG-"].update(0)
_VARS["window"]["Stop"].Update(disabled=True)
_VARS["window"]["Listen"].Update(disabled=False)


def pause():
if _VARS["stream"] and _VARS["stream"].is_active():
if _VARS["stream"].is_active():
_VARS["stream"].stop_stream()
_VARS["window"]["Pause"].Update(disabled=True)
_VARS["window"]["Resume"].Update(disabled=False)

def resume():
if _VARS["stream"] and not _VARS["stream"].is_active():
if not _VARS["stream"].is_active():
_VARS["stream"].start_stream()
_VARS["window"]["Pause"].Update(disabled=False)
_VARS["window"]["Resume"].Update(disabled=True)
Expand All @@ -100,29 +98,25 @@ def save():
sg.popup('Success', f'Audio saved as {folder}/output.wav')

def callback(in_data, frame_count, time_info, status):
try:
_VARS["audioData"] = np.frombuffer(in_data, dtype=np.int16)
_VARS["audioBuffer"] = np.append(_VARS["audioBuffer"], _VARS["audioData"])
except Exception as e:
print("Error in callback:", e)
traceback.print_exc()
global _VARS
audio_data = np.frombuffer(in_data, dtype=np.int16)
_VARS["audioBuffer"] = np.append(_VARS["audioBuffer"], audio_data)
_VARS["audioData"] = audio_data
return (in_data, pyaudio.paContinue)


def listen():
try:
_VARS["window"]["Stop"].Update(disabled=False)
_VARS["window"]["Listen"].Update(disabled=True)
_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:
sg.popup_error(f"Error: {e}")
_VARS["window"]["Stop"].Update(disabled=False)
_VARS["window"]["Listen"].Update(disabled=True)
_VARS["stream"] = pAud.open(
format=pyaudio.paInt16,
channels=1,
rate=RATE,
input=True,
frames_per_buffer=CHUNK,
stream_callback=callback,
)
_VARS["stream"].start_stream()

def close_current_visualizer():
if _VARS["current_visualizer_process"] and _VARS["current_visualizer_process"].poll() is None:
Expand All @@ -135,10 +129,17 @@ def close_current_visualizer():
# MAIN LOOP
while True:
event, values = _VARS["window"].read(timeout=TIMEOUT)
if event == "Exit" or event == sg.WIN_CLOSED:
if event == "Exit":
stop()
pAud.terminate()
break
# for handling the closing of application
if event == sg.WIN_CLOSED :
if _VARS["stream"]:
_VARS["stream"].stop_stream()
_VARS["stream"].close()
pAud.terminate()
break
if event == "Listen":
listen()
_VARS["window"]["Save"].Update(disabled=False)
Expand All @@ -154,38 +155,41 @@ def close_current_visualizer():
if event == 'Amplitude-Frequency-Visualizer':
close_current_visualizer()
_VARS["current_visualizer_process"] = subprocess.Popen(['python', 'Amplitude-Frequency-Visualizer.py'])
_VARS["window"].close()
_VARS["window"].close()
break
if event == 'Waveform':
close_current_visualizer()
_VARS["current_visualizer_process"] = subprocess.Popen(['python', 'Waveform.py'])
_VARS["window"].close()
_VARS["window"].close()
break
if event == 'Spectogram':
close_current_visualizer()
_VARS["current_visualizer_process"] = subprocess.Popen(['python', 'Spectogram.py'])
_VARS["window"].close()
_VARS["window"].close()
break
if event == 'Intensity-vs-Frequency-and-time':
close_current_visualizer()
_VARS["current_visualizer_process"] = subprocess.Popen(['python', 'Intensity-vs-Frequency-and-time.py'])
_VARS["window"].close()
_VARS["window"].close()
break
elif _VARS["audioData"].size != 0:
try:
_VARS["window"]["-PROG-"].update(np.amax(_VARS["audioData"]))
yf = scipy.fft.fft(_VARS["audioData"])
xf = np.linspace(0.0, RATE / 2, CHUNK // 2)
ax.clear()
ax.plot(
xf, 2.0 / CHUNK * np.abs(yf[: CHUNK // 2]), label='Frequency Spectrum'
)
ax.set_title("Frequency Spectrum") # Add this line to set the title
ax.set_ylabel("Amplitude")
ax.set_xlabel("Frequency [Hz]")
ax.grid(True) # Enable gridlines
ax.legend() # Add a legend
fig_agg.draw() # redraw the figure
except Exception as e:
print("Error during plotting:", e)
traceback.print_exc()
_VARS["window"]["-PROG-"].update(np.amax(_VARS["audioData"]))
yf = scipy.fft.fft(_VARS["audioData"])
xf = np.linspace(0.0, RATE / 2, CHUNK // 2)
ax.clear()
ax.plot(
xf, 2.0 / CHUNK * np.abs(yf[: CHUNK // 2]), label='Frequency Spectrum'
)
ax.set_ylabel("Amplitude")
ax.set_xlabel("Frequency [Hz]")
ax.grid(True) # Enable gridlines
ax.legend() # Add a legend
fig_agg.draw() # redraw the figure

# Check if the user wants to close the window
_VARS["window"].close()
# Clean up the audio stream and terminate PyAudio
if _VARS["stream"]:
_VARS["stream"].stop_stream()
_VARS["stream"].close()
pAud.terminate()
Loading