import os
import pygame
import tkinter as tk
from tkinter import filedialog
class MP3Player:
def __init__(self, master):
self.master = master
master.title("MP3 Player")
# Set up pygame mixer
pygame.mixer.init()
# Create playlist
self.playlist = []
# Create GUI
self.create_gui()
def create_gui(self):
# Create playlist label
self.playlist_label = tk.Label(self.master, text="Playlist")
self.playlist_label.pack()
# Create playlist listbox
self.playlist_listbox = tk.Listbox(self.master, height=10)
self.playlist_listbox.pack()
# Create open button
self.open_button = tk.Button(self.master, text="Open", command=self.open_file)
self.open_button.pack()
# Create play button
self.play_button = tk.Button(self.master, text="Play", command=self.play)
self.play_button.pack()
# Create pause button
self.pause_button = tk.Button(self.master, text="Pause", command=self.pause)
self.pause_button.pack()
# Create stop button
self.stop_button = tk.Button(self.master, text="Stop", command=self.stop)
self.stop_button.pack()
# Create timeline
self.timeline = tk.Scale(self.master, from_=0, to=100, orient=tk.HORIZONTAL, showvalue=False)
self.timeline.pack()
def open_file(self):
# Open file dialog
file_path = filedialog.askopenfilename(initialdir="/", title="Select file",
filetypes=(("mp3 files", "*.mp3"), ("all files", "*.*")))
# Add file to playlist
self.playlist.append(file_path)
self.playlist_listbox.insert(tk.END, os.path.basename(file_path))
def play(self):
# Get currently selected item in playlist
if not self.playlist_listbox.curselection():
return
self.current_index = self.playlist_listbox.curselection()[0]
# Get selected file path
file_path = self.playlist[self.current_index]
# Load and play selected file
self.sound = pygame.mixer.Sound(file_path)
self.sound.play()
def pause(self):
# Pause current playback
pygame.mixer.pause()
def stop(self):
# Stop current playback
pygame.mixer.stop()
def update_timeline(self):
# Get current playback position
pos = self.sound.get_pos() / 1000.0
# Update timeline position
self.timeline.set(pos)
# Schedule the next update
self.timeline.after(100, self.update_timeline)
root = tk.Tk()
mp3player = MP3Player(root)
mp3player.update_timeline()
root.mainloop()