-
Notifications
You must be signed in to change notification settings - Fork 0
/
ui.py
83 lines (64 loc) · 2.24 KB
/
ui.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import tkinter as tk
from tkinter import filedialog, messagebox
import pyaudio
import wave
import threading
import os
# Initialize Tkinter root
root = tk.Tk()
root.title("Sola Audio Player")
root.geometry("400x200")
chunk = 1024
p = pyaudio.PyAudio()
# Flag to stop audio playback
stop_flag = False
# Get the directory of the current script
base_dir = os.path.dirname(__file__)
# Construct the full path to the icons
open_img_path = os.path.join(base_dir, "app", "icons", "open.png")
stop_img_path = os.path.join(base_dir, "app", "icons", "stop.png")
# Load images for buttons (make sure the paths are correct)
open_img = tk.PhotoImage(file=open_img_path)
stop_img = tk.PhotoImage(file=stop_img_path)
# Function to open file dialog and play the audio
def play_audio():
global stop_flag
stop_flag = False
file = filedialog.askopenfilename(filetypes=[("WAV files", "*.wav")])
if not file:
return
try:
f = wave.open(file, 'rb')
stream = p.open(format=p.get_format_from_width(f.getsampwidth()),
channels=f.getnchannels(),
rate=f.getframerate(),
output=True)
data = f.readframes(chunk)
while data and not stop_flag:
stream.write(data)
data = f.readframes(chunk)
stream.stop_stream()
stream.close()
f.close()
if not stop_flag:
messagebox.showinfo("Playback", "Playback finished")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
# Function to start audio playback in a new thread
def start_audio_thread():
audio_thread = threading.Thread(target=play_audio)
audio_thread.start()
# Function to stop audio playback
def stop_audio_playback():
global stop_flag
stop_flag = True
# Add a button to play audio (with image)
play_button = tk.Button(root, image=open_img, command=start_audio_thread)
play_button.pack(pady=20)
# Add a stop button (with image)
stop_button = tk.Button(root, image=stop_img, command=stop_audio_playback)
stop_button.pack()
# Run the Tkinter event loop
root.mainloop()
# Clean up PyAudio resources when done
p.terminate()