0% found this document useful (0 votes)
10 views

How To Build A Music Player Using Python: The Tkinter, Pygame, and Os Module

Uploaded by

nikeonyemah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

How To Build A Music Player Using Python: The Tkinter, Pygame, and Os Module

Uploaded by

nikeonyemah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

How to Build a Music Player Using Python

By Sai Ashish Konchada – Published Mar 18, 2023

GameTips
Apple
Social
Mac
PlayStation
Instagram
Pay
Development
Media5 Tips

Python

 Follow  Share

Music players have evolved quickly with time. It began with Gramophones,
Jukeboxes, CD players, and MP3 players. Today, you can listen to music on your
mobile or computer itself. Exploring this very concept, develop a music player
application using Python and groove off.

The Tkinter, PyGame, and OS Module


To build the music player, you require the Tkinter, PyGame, and the OS module.
Tkinter is the standard GUI library for Python you can use to create desktop
applications. It offers a variety of widgets like buttons, labels, and text boxes so you
can develop apps in no time. To install Tkinter, open a terminal and execute:

pip install tkinter

Using PyGame you can develop amazing video games that can run on any platform.
It is simple to use and comes with graphic and sound libraries to make your
development process quicker. You will use PyGame's mixer.music module to provide
various functionalities to your music player. To install PyGame, execute:

pip install pygame

Finally, you need the OS module to load the songs into your system. The OS module
comes with the standard library of Python and doesn't need a separate installation.
With this module, you can access system-specific functions to deal with your
operating system.

How to Build a Music Player Using Python


Note
Link copied to clipboard
You can find the source code of the Music Player application using Python in
this GitHub repository.

Begin by importing the Tkinter, PyGame, and OS modules. Define a class,


MusicPlayer. Define the __init__ constructor that the program calls at the time of
object creation. You can use instance self to access any variables or methods within
the class.

Initialize the root window, and set the title, and dimensions of your music player.
Initialize all the imported PyGame modules along with the mixer module. Set track
and status to be of StringVar type. Using this, you can set a text value and retrieve it
when needed.

from tkinter import *


import pygame
import os

class MusicPlayer:

def __init__(self,root):
self.root = root
self.root.title("Music Player")
self.root.geometry("1000x200")
pygame.init()
pygame.mixer.init()
self.track = StringVar()
self.status = StringVar()

Define a LabelFrame that will contain the songttrack label and the trackstatus label.
Labelframe acts as a container and displays the labels inside a border area. Set the
parent window you want to place the frame in, the text it should display, the font
styles, the background color, the font color, the border width, and the 3D effects
outside the widget.

Use the place() method to organize the frame. Define two labels, songtrack and
trackstatus. Customize them and use the grid() manager to organize them in rows
and columns format. You can set the songtrack to be present in the first row and add
some padding to avoid overlap and make the design more beautiful.

trackframe = LabelFrame(self.root,text="Song Track",font=("arial",15,"bold"),bg="#8F00FF",fg="white"


trackframe.place(x=0,y=0,width=600,height=100)
songtrack = Label(trackframe,textvariable=self.track,width=20,font=("arial",24,"bold"),bg="#8F00FF"
trackstatus = Label(trackframe,textvariable=self.status,font=("arial",24,"bold"),bg="#8F00FF",fg="#B

Similarly, define a frame that will contain four buttons. Customize and organize it
below the trackframe. Define four buttons, Play, Pause, Unpause, and Stop. Set the
parent window you want to put the buttons in, the text it should display, the functions
it should execute when clicked, the width, height, font style, background color, and the
font color it should have.

Use the grid() manager to organize the buttons in a single row and four different
columns.

buttonframe = LabelFrame(self.root,text="Control Panel",font=("arial",15,"bold"),bg="#8F00FF",fg="wh


buttonframe.place(x=0,y=100,width=600,height=100)
playbtn = Button(buttonframe,text="PLAY",command=self.playsong,width=6,height=1,font=("arial",16,"bo
playbtn = Button(buttonframe,text="PAUSE",command=self.pausesong,width=8,height=1,font=("arial",16,"
playbtn = Button(buttonframe,text="UNPAUSE",command=self.unpausesong,width=10,height=1,font=("arial"
Link copied to clipboard playbtn = Button(buttonframe,text="STOP",command=self.stopsong,width=6,height=1,font=("arial",16,"bo

Define a LabelFrame, songframe. This will contain the songs you want to play on your
music player. Customize the properties of the frame and place it on the right side of
the track and button frame. Add a vertical scroll bar to access the songs even when
your song list is long.

Use the Listbox widget to display the songs. Set the background color to display
when you select the text, and the mode. The single mode allows you to select one
song at a time. Additionally, initialize the font style, the background color, the font
color, the border width, and the 3D style you want around it.

songsframe = LabelFrame(self.root,text="Song Playlist",font=("arial",15,"bold"),bg="#8F00FF",fg="whi


songsframe.place(x=600,y=0,width=400,height=200)
scroll_y = Scrollbar(songsframe,orient=VERTICAL)
self.playlist = Listbox(songsframe,yscrollcommand=scroll_y.set,selectbackground="#B0FC38",selectmode

Pack the scrollbar to the right-hand side of the window and fill it as Y. This ensures
that whenever you expand the window, the Scrollbar expands in the Y direction too.
Configure the list box to use the yview method of the scrollbar to scroll vertically.
Pack the list box to take the space both horizontally and vertically.

Change the current working directory to the specified path. Iterate over the songs and
insert them into the list box one by one. You use END as the first argument as you
want to add new lines to the end of the listbox.

scroll_y.pack(side=RIGHT,fill=Y)
scroll_y.config(command=self.playlist.yview)
self.playlist.pack(fill=BOTH)
os.chdir("Path_to_your_songs_folder")
songtracks = os.listdir()
for track in songtracks:
self.playlist.insert(END,track)

Define a function, playsong. Set the track to display the name of the song along with
the status as -Playing. Use the load() and play() functions of PyGame's mixer.music
module to load music for playback and start it.

def playsong(self):
self.track.set(self.playlist.get(ACTIVE))
self.status.set("-Playing")
pygame.mixer.music.load(self.playlist.get(ACTIVE))
pygame.mixer.music.play()

Similarly, define functions to stop, pause and unpause the songs using stop(),
pause(), and unpause().

def stopsong(self):
self.status.set("-Stopped")
pygame.mixer.music.stop()

def pausesong(self):
self.status.set("-Paused")
pygame.mixer.music.pause()

def unpausesong(self):
self.status.set("-Playing")
Link copied to clipboard pygame.mixer.music.unpause()

Initialize the Tkinter instance and display the root window by passing it to the class.
The mainloop() function tells Python to run the Tkinter event loop and listen for
events until you close the window.

root = Tk()
MusicPlayer(root)
root.mainloop()

Put all the code together, and you have your music player ready to play at your
fingertips. You can customize your music player even further by adding objects and
shapes using PyGame's drawing modules.

Output of Music Player Application Using Python


On running the program, the music player launches the songs you selected as a
playlist. On choosing any of the songs and hitting on the Play button, the music
starts playing. Similarly, the music pauses, unpauses, and stops playing with the click
of the appropriate buttons.

Building Games With PyGame Module


PyGame is a powerful module that you can use to build games like Frets on Fire,
Flappy Bird, Snake, Super Potato Bruh, Sudoku, and more. PyGame has an object-
oriented design, so you can reuse codes and customize the characters of your games
easily.

It supports and provides great graphics, sounds, input, and output tools, so you can
focus on designing your game rather than investing your time in coding every single
minute feature. Alternatively, you can explore Pyglet and Kivy which are faster,
supports 3D projects, are more intuitive, and comes with regular updates.

Programming Python Game…

 Follow    

Readers like you help support MakeUseOf. When you make a purchase using links on our site, we may earn an affiliate commission. Read More.

 RECOMMENDED
Adding
Link Sound
copied Effects
to clipboard and Music in How to Use Apple Pay in Stores and How I Prevent Social Media From
Pygame Online Distracting Me During the Day
Give your gamers something to listen to while they Learn to use Apple's contactless payment service for It's tempting to keep checking social media apps, so
play with Pygame’s music and sound effects in-store and online purchases. here's how I keep them from distracting me when I
features. need to be productive.

Feb 7, 2023  3 days ago  6 hours ago 

2 Ways to Create a Bootable Windows 11 Instagram's Latest Bug Is Why I'm Here's How I Find In-Game Hints on My
USB With a Mac Backing Up All My Stories From Now On PS5
You don't need a Windows PC to create a bootable An Instagram bug has led to the loss of certain story Game hints on the PS5 can help you when you're
Windows 11 installer. posts for some users. stuck.

45 minutes ago  3 days ago 1 23 hours ago 

Join Our Team


Our Audience
About Us
Press & Events
Contact Us

Follow Us      

Advertising
Careers
Terms
Privacy
Policies

MUO is part of the Valnet Publishing Group

Copyright © 2024 Valnet Inc.

You might also like