stream_queue.py
1.96 KB
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
import pyaudio
import numpy as np
import tkinter as tk
from threading import Thread
from queue import Queue
from mutagen.mp3 import MP3
class MP3Player:
def __init__(self):
self.filename = "./sounds/s4.mp3"
self.audio = pyaudio.PyAudio()
self.stream = None
self.isPlaying = False
self.chunk = 1024
self.queue = Queue()
def load_mp3_file(self):
audio_info = MP3(self.filename)
self.sample_rate = audio_info.info.sample_rate
self.channels = audio_info.info.channels
def start_stream(self):
self.stream = self.audio.open(format=pyaudio.paFloat32,
channels=self.channels,
rate=self.sample_rate,
output=True,
output_device_index=2,
stream_callback=self.callback)
self.stream.start_stream()
def stop_stream(self):
if self.stream:
self.stream.stop_stream()
self.stream.close()
self.stream = None
def play(self):
self.load_mp3_file()
self.start_stream()
self.isPlaying = True
def pause(self):
if self.isPlaying:
self.stop_stream()
self.isPlaying = False
def callback(self, in_data, frame_count, time_info, status):
data = self.queue.get()
return (data, pyaudio.paContinue)
def enqueue_data(self, data):
self.queue.put(data)
def create_gui(self):
self.root = tk.Tk()
self.root.title("MP3 Player")
self.play_button = tk.Button(self.root, text="Play", command=self.play)
self.play_button.pack(pady=10)
self.pause_button = tk.Button(self.root, text="Pause", command=self.pause)
self.pause_button.pack(pady=10)
self.root.mainloop()
if __name__ == "__main__":
player = MP3Player()
player.create_gui()