stream_queue.py 1.96 KB
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()