Certainly! Below is a simple example of a music player using Python with tkinter for the GUI and python-vlc for media playback. It includes:
- A file picker to select an audio file.
- A Play/Pause button.
- A slider that shows the progress and allows seeking.
Make sure you have the required packages installed:
bash
pip install python-vlc
Also, VLC media player must be installed on your system because python-vlc is just a wrapper around the VLC libraries.
Music Player Code
python
import tkinter as tk
from tkinter import filedialog
import vlc
import time
import threading
class MusicPlayer:
def __init__(self, root):
self.root = root
self.root.title("Python VLC Music Player")
self.root.geometry("400x150")
# VLC player instance
self.instance = vlc.Instance()
self.player = self.instance.media_player_new()
# Variables
self.is_paused = True
self.duration = 0
# UI Elements
self.create_widgets()
# Update slider in a separate thread
self.update_thread = threading.Thread(target=self.update_slider, daemon=True)
self.update_thread.start()
def create_widgets(self):
# File picker button
self.btn_open = tk.Button(self.root, text="Open File", command=self.open_file)
self.btn_open.pack(pady=10)
# Play/Pause button
self.btn_play = tk.Button(self.root, text="Play", command=self.play_pause, state=tk.DISABLED)
self.btn_play.pack(pady=5)
# Slider for progress
self.scale = tk.Scale(self.root, from_=0, to=1000, orient=tk.HORIZONTAL, length=300, command=self.seek)
self.scale.pack(pady=10)
def open_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Audio Files", "*.mp3 *.wav *.flac *.ogg")])
if file_path:
media = self.instance.media_new(file_path)
self.player.set_media(media)
self.player.play()
time.sleep(0.1) # Wait a bit for the player to start
self.duration = self.player.get_length() / 1000 # duration in seconds
self.scale.config(to=int(self.duration * 1000))
self.is_paused = False
self.btn_play.config(text="Pause", state=tk.NORMAL)
def play_pause(self):
if self.player.is_playing():
self.player.pause()
self.is_paused = True
self.btn_play.config(text="Play")
else:
self.player.play()
self.is_paused = False
self.btn_play.config(text="Pause")
def update_slider(self):
while True:
if not self.is_paused and self.player.is_playing():
current_time = self.player.get_time() # milliseconds
if current_time >= 0:
self.scale.set(current_time)
time.sleep(0.5)
def seek(self, val):
# Seek to the position in milliseconds
pos = int(val)
self.player.set_time(pos)
if __name__ == "__main__":
root = tk.Tk()
app = MusicPlayer(root)
root.mainloop()
How it works:
- Click Open File to select an audio file.
- The player will start playing automatically.
- Use the Play/Pause button to toggle playback.
- The slider shows the current playback position and can be dragged to seek.
If you want me to add volume control or playlist support, just ask!