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
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 pygameimport osclass MusicPlayer: def __init__(self,root): self.root = root self.root.title(“Music Player”) self.root.geometry(“1000×200”) 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”,bd=5,relief=GROOVE) trackframe.place(x=0,y=0,width=600,height=100) songtrack = Label(trackframe,textvariable=self.track,width=20,font=(“arial”,24,”bold”),bg=”#8F00FF”,fg=”#B0FC38″).grid(row=0,column=0,padx=10,pady=5) trackstatus = Label(trackframe,textvariable=self.status,font=(“arial”,24,”bold”),bg=”#8F00FF”,fg=”#B0FC38″).grid(row=0,column=1,padx=10,pady=5)
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=”white”,bd=5,relief=GROOVE) 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,”bold”),fg=”navyblue”,bg=”#B0FC38″).grid(row=0,column=0,padx=10,pady=5) playbtn = Button(buttonframe,text=”PAUSE”,command=self.pausesong,width=8,height=1,font=(“arial”,16,”bold”),fg=”navyblue”,bg=”#B0FC38″).grid(row=0,column=1,padx=10,pady=5) playbtn = Button(buttonframe,text=”UNPAUSE”,command=self.unpausesong,width=10,height=1,font=(“arial”,16,”bold”),fg=”navyblue”,bg=”#B0FC38″).grid(row=0,column=2,padx=10,pady=5) playbtn = Button(buttonframe,text=”STOP”,command=self.stopsong,width=6,height=1,font=(“arial”,16,”bold”),fg=”navyblue”,bg=”#B0FC38″).grid(row=0,column=3,padx=10,pady=5)
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=”white”,bd=5,relief=GROOVE) 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=SINGLE,font=(“arial”,12,”bold”),bg=”#CF9FFF”,fg=”navyblue”,bd=5,relief=GROOVE)
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”) 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.