How to Create an MP3 Music Player Using Python

7135 VIEWS

· ·

One good thing about music is that when it hits you, you feel no pain. In today’s society everybody loves listening to music and many people consider it a hobby.

In order for us to listen to music freely and without any kind of disturbance from the forced ads we get from the apps available, utilizing our skills can be essential. Using Python we can create a music player app that serves the same purpose as the already existing ones only this time it’s our creation and of course ads free.

Python Music Player

The advancement in technology has led to development of many MP3 music player apps. These apps have a range of functionality and capabilities. As a result, it is hard to choose which is the best among them all.

Additionally, these MP3 music player apps will prompt you to pay a subscription fee or you will be forced to endure ads. 

Fortunately, with Python and some of its libraries you can get a fully functional app with features like: 

  • Open music files,
  • Play music, 
  • Pause music, 
  • Unpause, 
  • Stop music just to mention some of the common features.

In this tutorial we will be utilizing our knowledge in Python to achieve this. Now, it’s time to implement the above mentioned features.

Let’s get started.

Project Requirements

Now, before we get started with the fun part of this project which is writing the code, we need to make sure that we have every necessary tool for this task ready.

For us to work on this MP3 music player having basic understanding of Python programming language is necessary, apart from this also some basic knowledge in python libraries will be helpful (we discuss about libraries next sub-topic).

Also, make sure that you have Python installed in your machine and a code editor, too. In this case any code editor will be fine, including Pycharm, VS Code, Atom or any of your choice.

Use the command below to check whether Python is installed. This command works no matter the operating system you are using, including Windows, Mac and Linux systems:

python --version

Having ensured that we have everything set correctly from this step, we can now move to the next step that is installing necessary libraries required for this particular project.

Python Libraries Needed

In order for us to have our application up and running, we will need to make use of some Python libraries that will make it easier to develop the application by adding some functionalities and interactivity to our application. They include:

  • Tkinter – Used to create a GUI interface for our application.
  • Pygame – Used to include the sound libraries designed to be used with Python.

Now that we have the main libraries required, let’s get started with our development with a step by step guide through each step accompanied with an explanation of what is happening.

You can also get access to the project code available on GitHub here.

Steps to Develop MP3 Music Player App

For a successful implementation of this project we will be following the steps below:

  • Install and import necessary libraries.
  • Create the project layout.
  • Define the music player main functions.
Step 1: Installing the libraries

To get started we need to install the pygame library. We will use PIP to run the installation command.

pip install pygame

Similarly to install tkinter we will make use of PIP by executing the command below:

pip install tk
Step 2: Import Important Libraries

In order for us to use the modules that we have installed, we will need to import them, specifically some packages that align with our project.

The code below allows us to do this. Remember, all the code is written in a python file, make sure you already have one created:

#importing libraries 

import os
from tkinter import *
from tkinter import Tk
from tkinter import filedialog
from pygame import mixer

We begin by import os which is the functional module that will help us get data from our computers. Next, tkinter module is imported; it is the standard module which will be used to create a GUI and by adding the * sign means we import everything within the library, filedialog is also imported which will help in operations like opening files or directories. The import mixer command will be used for manipulation of the song.

Step 3: Create Root Window

At this point we have everything necessary to initialize a root window for our project. The root window is going to be the layout of our app housing all components needed including different functional buttons for interactivity. With the code below we are able to set the window title and also the dimensions. (Feel free to try out different dimensions you are comfortable with).

# Create a GUI window
root = Tk()
root.title("Music Player")
root.geometry("920x600+290+85")
root.configure(background='#212121')
root.resizable(False, False)
mixer.init()

The root = Tk() is used to create an instance of the tkinter frame which will help display the rot window and also manage other components of the tkinter applications. Just as the name suggests, root.title() sets the title of the music player which will display at the top of the window (feel free to give it a title of your liking).

In order to get the window size the root.geometry() is used, and .configure() is used to give our window a background color. When using tkinter you are given the option to automatically resize the window size which at some point might interfere with the look of your display, now to avoid that the .resizable() to False. And finally we initialize the pygame mixer module by using the command mixer.init().

Step 4: Loading Music

First we begin by creating a function def AddMusic(), which will allow us to pass in the code that will be used to load music to our MP3 player.

# Create a function to open a file
def AddMusic():
    path = filedialog.askdirectory()
    if path:
        os.chdir(path)
        songs = os.listdir(path)

        for song in songs:
            if song.endswith(".mp3"):
                Playlist.insert(END, song)


def PlayMusic():
    Music_Name = Playlist.get(ACTIVE)
    print(Music_Name[0:-4])
    mixer.music.load(Playlist.get(ACTIVE))
    mixer.music.play()

Under the AddMusic() function we have different parameters set in place. First we begin by defining a variable name path which is set to ask the user to select a directory containing the music. We then make use of an if-loop statement in which the directory path is passed, which will enable us to open any folder where music is saved.

We also have the PlayMusic() function, which will play whichever song is selected from the existing files.

Step 5: Branding Our App

When using tkinter, we are able to gain access to multiple features, some of which include the ability to add images to our app. In our case the only image we will add for now is a logo and icon which will act as a sense of branding to our project. For this we will make use of the PhotoImage widget which will return the passed images on our display.

# icon
image_icon = PhotoImage(file="PATH_TO_LOGO")
root.iconphoto(False, image_icon)

Top = PhotoImage(file="PATH_TO_LOGO")
Label(root, image=Top, bg="#0f1a2b").pack()

# logo
logo = PhotoImage(file="PATH_TO_LOGO")
Label(root, image=logo, bg="#0f1a2b", bd=0).place(x=70, y=115)

NOTE: For the icon and the logo, we specified image paths to specific files, make sure you have a logo and an icon in place for this particular step.

Step 6: Creating Interactive Buttons and Labels

This particular step is where we get to design the interface of our app that includes adding the canvas to display the song being played and buttons to perform different operations, setting the fonts, colors, text position etc…

Step 6.1: Buttons

To create the buttons we use the tkinter module. Some of the useful buttons we will need at this point will include the play, pause, stop and resume button. To make the buttons look eye catchy we will be using some designed icons, each corresponding to each command it performs.

# Button
ButtonPlay = PhotoImage(file="PATH_TO_IMAGE")
Button(root, image=ButtonPlay, bg="#0f1a2b", bd=0,
       command=PlayMusic).place(x=100, y=400)

ButtonStop = PhotoImage(file="PATH_TO_IMAGE")
Button(root, image=ButtonStop, bg="#0f1a2b", bd=0,
       command=mixer.music.stop).place(x=30, y=500)

ButtonResume = PhotoImage(file="PATH_TO_IMAGE")
Button(root, image=ButtonResume, bg="#0f1a2b", bd=0,
       command=mixer.music.unpause).place(x=115, y=500)

ButtonPause = PhotoImage(file="PATH_TO_IMAGE")
Button(root, image=ButtonPause, bg="#0f1a2b", bd=0,
       command=mixer.music.pause).place(x=200, y=500)

Under each button method the same procedure is followed. We first begin by passing the corresponding name followed by the icon that explains the method, this is just for visuality. We then add some background color and invoke the mixer command which will be called when the button is clicked, like in the first case it will initialize the stop command.

Step 6.2: Labels

Under this section we add some extra functionality to enhance the look of our app. Some of the additional features include adding fonts, creating a frame which will be used to display our playlist and also adding a scrollbar.

Remember that with tkinter you can always add as many features as possible. There is no limit to the number of functionality a music app can perform.

# Label 
Menu = PhotoImage(file="PATH_TO_IMAGE")
Label(root, image=Menu, bg="#0f1a2b").pack(padx=10, pady=50, side=RIGHT)

Frame_Music = Frame(root, bd=2, relief=RIDGE)
Frame_Music.place(x=330, y=350, width=560, height=250)

Button(root, text="Open Folder", width=15, height=2, font=("times new roman",
       12, "bold"), fg="Black", bg="#21b3de", command=AddMusic).place(x=330, y=300)

Scroll = Scrollbar(Frame_Music)
Playlist = Listbox(Frame_Music, width=100, font=("Times new roman", 10), bg="#333333", fg="grey", selectbackground="lightblue", cursor="hand2", bd=0, yscrollcommand=Scroll.set)
Scroll.config(command=Playlist.yview)
Scroll.pack(side=RIGHT, fill=Y)
Playlist.pack(side=LEFT, fill=BOTH)

Now, we only have to do one more step. We just have to add the last piece of code that will execute the program.

Step 7: Run the App

To execute the app we use the mainloop() method. What it does is, it tells Python to run the tkinter event loop until the user exits it.

# Execute Tkinter

root.mainloop()
The Output

Running the above code will create a display of our MP3 music player app. An example of this display is shown below with everything set as defined in the code.

Now, let’s get add some music to the player to be sure everything is working out fine:

From the screenshots above, we have successfully uploaded music into our MP3 player. Feel free to play with different features provided.

It’s important to also highlight that with the two libraries we have used here, you can do more than just the listed features provided in our code. You can also add the next button, previous button, skip ahead button just to mention a few. To learn more about how to implement this and more, check out the official Tkinter and Pygame documentation.

Conclusion

Now you can create your own MP3 music player app using Python that is just like other softwares out there. You can also add more features that we haven’t explored yet.

There is no limitation on the design of the app. What we have just done here is a small percentage of all possible designs. You can redesign it to meet your own specification and style by adding your own icons, logo, button designs etc. It’s about time you start using your own creations.


Hillary ("Lary") Nyakundi is a Growing Developer, with great interest in technology, open-source and the Python programming language. He is also a technical writer aiming to help share knowledge with other developers through informative articles. Through this, he has been able to work with tech companies from the US, India and Kenya. His passion in the developer world led him to start a podcast, “Let’s Talk Developer” where he gets to connect with other developers, learn from them and share their stories to help inspire upcoming developers.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar