3 min read

Basic MP3 Player

This guide demonstrates how to build a simple desktop MP3 player with a Graphical User Interface (GUI). It allows you to load a folder of music, view a playlist, and control playback (Play, Pause, Stop, Next, Previous).

Modules Used:

  • pygame: Specifically the mixer module, used for loading and playing audio files.
  • tkinter: The standard Python interface to the Tcl/Tk GUI toolkit.
  • os: To interact with the file system and list music files.

Installation

You need to install pygame. tkinter and os are included in the standard library.

pip install pygame

The Code

Save this as player.py.

import tkinter as tk
from tkinter import filedialog
import pygame
import os

class MusicPlayer:
    def __init__(self, root):
        self.root = root
        self.root.title("Python MP3 Player")
        self.root.geometry("500x350")

        # Initialize Pygame Mixer
        pygame.mixer.init()

        # Variables
        self.playlist = []
        self.current_song = ""
        self.paused = False

        # --- UI Components ---

        # Song List
        self.song_listbox = tk.Listbox(root, bg="black", fg="white", width=60, height=15)
        self.song_listbox.pack(pady=20)

        # Control Buttons Frame
        control_frame = tk.Frame(root)
        control_frame.pack()

        # Buttons
        btn_prev = tk.Button(control_frame, text="<<", command=self.prev_song, width=5)
        btn_prev.grid(row=0, column=0, padx=10)

        btn_play = tk.Button(control_frame, text="Play", command=self.play_music, width=5)
        btn_play.grid(row=0, column=1, padx=10)

        btn_pause = tk.Button(control_frame, text="Pause", command=self.pause_music, width=5)
        btn_pause.grid(row=0, column=2, padx=10)

        btn_stop = tk.Button(control_frame, text="Stop", command=self.stop_music, width=5)
        btn_stop.grid(row=0, column=3, padx=10)

        btn_next = tk.Button(control_frame, text=">>", command=self.next_song, width=5)
        btn_next.grid(row=0, column=4, padx=10)

        # Menu
        menubar = tk.Menu(root)
        root.config(menu=menubar)
        file_menu = tk.Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=file_menu)
        file_menu.add_command(label="Load Folder", command=self.load_folder)

    def load_folder(self):
        directory = filedialog.askdirectory()
        if directory:
            os.chdir(directory)
            songs = os.listdir(directory)

            self.playlist.clear()
            self.song_listbox.delete(0, tk.END)

            for song in songs:
                if song.endswith(".mp3"):
                    self.playlist.append(song)
                    self.song_listbox.insert(tk.END, song)

    def play_music(self):
        try:
            selected_index = self.song_listbox.curselection()
            if selected_index:
                song_name = self.song_listbox.get(selected_index)

                # If playing a new song
                if song_name != self.current_song:
                    self.current_song = song_name
                    pygame.mixer.music.load(song_name)
                    pygame.mixer.music.play()
                    self.paused = False
                elif self.paused:
                    pygame.mixer.music.unpause()
                    self.paused = False
        except Exception as e:
            print(f"Error playing song: {e}")

    def pause_music(self):
        if not self.paused:
            pygame.mixer.music.pause()
            self.paused = True
        else:
            pygame.mixer.music.unpause()
            self.paused = False

    def stop_music(self):
        pygame.mixer.music.stop()
        self.song_listbox.selection_clear(0, tk.END)
        self.current_song = ""

    def next_song(self):
        self._change_song(1)

    def prev_song(self):
        self._change_song(-1)

    def _change_song(self, direction):
        try:
            current_selection = self.song_listbox.curselection()
            if current_selection:
                next_index = current_selection[0] + direction
                if 0 <= next_index < self.song_listbox.size():
                    self.song_listbox.selection_clear(0, tk.END)
                    self.song_listbox.selection_set(next_index)
                    self.song_listbox.activate(next_index)
                    self.play_music()
        except Exception:
            pass

if __name__ == "__main__":
    root = tk.Tk()
    app = MusicPlayer(root)
    root.mainloop()

Usage

  1. Run the script:
    python player.py
  2. Click File -> Load Folder.
  3. Select a directory on your computer that contains .mp3 files.
  4. Select a song from the list and click Play.

programming/python/python