DEV Community

Cover image for Build a Music Player Using Python.
Ebikara Dandeson Spiff
Ebikara Dandeson Spiff

Posted on • Updated on

Build a Music Player Using Python.

Introduction

Have you ever wanted to explore how music and technology come together? In this article, we're going on a fun journey to make a Music Player that music lovers will enjoy, all while showing off Python's skills in music tech.

We’re not just making any old music player here. We're building a tool that will make listening to music better and smoother for everyone. By mixing Python with cool tools like Tkinter for the design, pygame for playing music, os for handling files, and fnmatch for matching patterns, we're making a music player that’s useful and enjoyable.

Let us dive into Python programming, explore how to make interfaces with Tkinter, and use pygame to play music. This article will be your guide, taking you through each step as we create our very own Music Player using the magic of Python. Let's see how we can mix code with melodies to make a cool music experience

Setting Up The Project Environment

When working in Visual Studio Code (VS Code), create a new Python file for our music player project.
It's helpful to have separate files for different parts of your project.

Create a new Python application:

To do this, you can start by opening your VS Code and creating a new folder:

Step 1

Open VS Code

vs code front page

Step 2

Create new folder

image of a new vs code folder

Step 3

Head over to the newly created folder and create a new file called app.py.

Image of vs code file

Install the necessary libraries

Before we dive into the technical details, Let's start by installing and importing the necessary libraries and modules.

First, we begin by importing the necessary library - pygame in Python:

pip install pygame
Enter fullscreen mode Exit fullscreen mode

Installed pygame library

Step 1

We will create this music player with Python using Tkinter, fnmatch, os and pygame.

First, we import all the necessary libraries and modules that we need:

import tkinter as tk
import fnmatch
import os
from pygame import mixer 
Enter fullscreen mode Exit fullscreen mode

Designing the User Interface

So, when we talk about this, it's basically about setting up all the stuff you see and use to play music on a screen. You know, like figuring out how everything should look, where the buttons go, how the sliders work, and all those parts that make it easy and smooth for you to use the music player.

Step 1

First off, we kickstart our music player application by creating what we call the canvas.
This canvas is like the main stage where all the interactive elements of our music player will perform. We do this by calling an instance of a Tkinter window with tk.Tk():

canvas = tk.Tk( )
Enter fullscreen mode Exit fullscreen mode

Step 2

Next, we give our canvas a distinct identity by setting it's title to Music Player using canvas.title("Music Player"). This title acts as a welcoming sign at the top of the window, letting users know exactly what this application is all about:

canvas.title("Music Player")
Enter fullscreen mode Exit fullscreen mode

Step 3

To ensure our music player occupies just the right space on the screen, we specify the dimensions of the window using canvas.geometry('600x800'). This step allows us to fine-tune the width and height of the interface for optimal user experience:

canvas.geometry(''600x800")
Enter fullscreen mode Exit fullscreen mode

Step 4

Next, we want to change the background color of our canvas, by changing the background color of our window to a stylish black shade using canvas.config(bg='black'), we add a touch of elegance to the music player's visual appeal. This sets the stage for a sleek and modern design:

canvas.config(bg = 'black')
Enter fullscreen mode Exit fullscreen mode

Step 5

Lastly, let's save and run our code:

canvas.mainloop( )
Enter fullscreen mode Exit fullscreen mode

main window interface

Loading and displaying music files

Loading and displaying music files is like setting up the backstage area so that your music player knows which songs to play and where to show them on the screen.

Picture it like organizing your music collection into a neat library for easy access and visual enjoyment.

Step 1

In this step we want to show music from a particular folder. Think of it like telling your music player where to find the songs. Imagine giving it directions like you would tell a friend how to find your house. The rootpath is just a term to hold the location (path) of your music folder. In this case:

rootpath = "C:\\Users\evane\Desktop\music"
Enter fullscreen mode Exit fullscreen mode

Step 2

Now, we need to make sure our music player only picks mp3 files from the folder. It's like telling it to ignore all other types of files. We create a variable pattern for this specific file type:

pattern = "*.mp3"
Enter fullscreen mode Exit fullscreen mode

Step 3

Here, We are creating a space to display the song list, kind of like setting up the screen where your songs are shown. this is our listBox:

listBox = tk.Listbox( canvas, fg = "cyan", bg =    "black", width =  100, font = ('ds-digital', 14)) 
 listBox.pack (padx= 15, pady= 15)
Enter fullscreen mode Exit fullscreen mode

Step 4

Next, we are going through the music folder, checking each file. It's like flipping through your music collection, examining every song in the folder with the for loop:

 for root, dirs, files in os.walk(rootpath) : 
      for filename in fnmatch.filter(files, pattern)
           listBox.index( 'end', filename )
Enter fullscreen mode Exit fullscreen mode

Step 5

Save and run to see all the mp3 files inside our music player listbox.

image of mp3 files inside our music player listbox.<br>

Designing a clean and intuitive user interface: buttons, playlist display

When we say we're building a music player with Python and focusing on designing a clean and intuitive user interface with buttons and playlist display, we're essentially aiming to create a program that looks nice, is easy to navigate, and allows you to manage your music collection effortlessly.

Step 1

In this step, we are setting up a label to display selected songs on our interface. We will create a variable label with specific text, background color, foreground color, and font:

 Label = tk.Label(canvas, text = ' ', bg = 'black' fg = 'yelow', font = ('ds-digital', 18)
Enter fullscreen mode Exit fullscreen mode

Step 2

After creating the label, we need to display it on our canvas. To do this we use the pack method to place the label on the canvas with some padding:

 Label = tk.Label(canvas, text = ' ', bg = 'black' fg = 'yelow', font = ('ds-digital', 18)
  Label.pack( pady = 15 )
Enter fullscreen mode Exit fullscreen mode

Step 3

Here, we are creating a frame named top to organize our labels in a horizontal order. This frame will be used to hold other elements like buttons:

  top = tk.Frame(canvas bg ="black")
  top.pack(padx = 10, pady = 5, anchor = 'center')
Enter fullscreen mode Exit fullscreen mode

Step 4

Next We're adding a button called prevButton to allow users to skip to the previous song:

prevButton = tk.Buttons(canvas, text = "Prev") 
Enter fullscreen mode Exit fullscreen mode

Step 5

We are packing the prevButton to display it on our interface, we want to ensure it appears on the left side of the top frame:

  prevButton = tk.Buttons(canvas, text = "Prev")
  prevButton.pack(pady = 15, in_ = top, side = 'left') 

  stopButton = tk.Buttons(canvas, text = "Stop")
  prevButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 6

Next, let's add some images to our buttons to give it a beautiful interface. We already have some images that we downloaded

Image of music buttons

To use this we have to select all the icons and copy them, then right-click on the Python file you created at the beginning and click on reveal in File Explorer then paste the icons.

selected image of music buttons

Next, your icons should be showing under the Python file you created in your VS Code.

Music icons in created python file

Step 7

Here, we initialize the images for the buttons by loading them from image files on disk using the tk.PhotoImage class:

prev_img = tk.PhotoImage(file = " prev_img.png ")

stop_img = tk.PhotoImage(file = " stop_img.png ")

play_img = tk.PhotoImage(file = " play_img.png ")

pause_img = tk.PhotoImage(file = " pause_img.png ")

next_img = tk.PhotoImage(file = " next_img.png ")
Enter fullscreen mode Exit fullscreen mode

Step 8

Now that the images are initialized, we add each image to its respective button to visually represent functions like prev, stop, play, pause, and next:

  prevButton = tk.Buttons(canvas, text = "Prev", image = prev_img, bg = 'black', borderwidth = 0 )
  prevButton.pack(pady = 15, in_ = top, side = 'left') `

` stopButton = tk.Buttons(canvas, text = "Stop", image = stop_img, bg = 'black', borderwidth = 0 )
  stopButton.pack(pady = 15, in_ = top, side = 'left') `

` playButton = tk.Buttons(canvas, text = "Play", image = play_img, bg = 'black', borderwidth = 0 )
  playButton.pack(pady = 15, in_ = top, side = 'left') `

` pauseButton = tk.Buttons(canvas, text = "Pause", image = pause_img, bg = 'black', borderwidth = 0 )
  pauseButton.pack(pady = 15, in_ = top, side = 'left') `

` nextButton = tk.Buttons(canvas, text = "Next", image = next_img, bg = 'black', borderwidth = 0)
  nextButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 9

Now, let's save it and run our code.

Music icons in playlist

Implementing Core Functionality

When implementing core functionality, we will be writing code to handle key actions like playing songs, pausing, skipping tracks, creating playlists, etc. This foundational code will be the backbone of our music player, allowing users to interact with it smoothly.

Step 1

In this step, we plan to create a new method called select() which we will use to handle the functionality when we select and play a song:

 def select( ) :
Enter fullscreen mode Exit fullscreen mode

Step 2

When we select a song from the list and click on the play button, it should show the name of the song inside the label and also play the song:

 def select( ) :
     label.config(text = listBox.get("anchor"))
Enter fullscreen mode Exit fullscreen mode

Step 3

After we've picked the song and updated the label, We will use mixer.music.load() to load the song and mixer.music.play() to start playing it:

 def select( ) :
     label.config(text = listBox.get("anchor"))
     mixer.music.load( rootpath + " \\ "  + listBox.get("anchor"))
     mixer.music.play( )
Enter fullscreen mode Exit fullscreen mode

Step 4

Next, we will initialize our mixer:

mixer.init ()
Enter fullscreen mode Exit fullscreen mode

Step 5

To set up the Play button, we will create a button widget that includes an image. When this button is clicked, it should call the select() method. This way, whenever we click the button, it triggers the select() method:

playButton = tk.Buttons(canvas, text = "Play", image = play_img, bg = 'black', borderwidth = 0, command = select )
  playButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 6

We will define a new method called stop() that will stop the song that is currently playing:

def stop( ) :
     mixer.music.stop( )
Enter fullscreen mode Exit fullscreen mode

Step 7

When we hit the stop button, we'll make sure to clear the selection of the currently playing song from the list. This way, the user will see a clean slate, and no song will be highlighted or selected after they stop the music.

This is a small but important step towards giving them a smooth and intuitive experience while using the app:

 listBox.select_clear('active')
Enter fullscreen mode Exit fullscreen mode

Step 8

To add a stop button for the song, we will create another button in our code and associate it with the stop() method. When we click on this stop button, it will call the stop() method to halt the song:

 stopButton = tk.Buttons(canvas, text = "Stop", image = stop_img, bg = 'black', borderwidth = 0, command = stop)
  stopButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 9

Next, we will create a method called play_next() that will get us ready to play the next song in the playlist. First, we need to make sure we're set up to handle the next track:

def play_next ( ):
     next_song  = listBox.curselection()
     next_song = next_song[0] +1
Enter fullscreen mode Exit fullscreen mode

Step 10

To get the song name of the next song and update it in the label:

next_song_name = listBox.get(next_song)
label.config(text = next_song_name)
Enter fullscreen mode Exit fullscreen mode

Step 11

Next, we need to play the next song also, to do this :

     mixer.music.load( rootpath + " \\ "  + next_song_name)
     mixer.music.play( ) 
Enter fullscreen mode Exit fullscreen mode

Step 12

Now, we want to clear the current selection, move on to the next song, and update the list to focus on the song that's playing next:

listBox.select_clear(0,'end')
listBox.activate(next_song)
listen.select_set(next_song)
Enter fullscreen mode Exit fullscreen mode

Step 13

Next, to create a button that plays the next song when clicked, we will use the play_next() method. We will add an event listener to the button so that when it's clicked, the play_next() method is activated:

 nextButton = tk.Buttons(canvas, text = "Next", image = next_img, bg = 'black', borderwidth = 0, command = play_next)
  nextButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 14

Next, we work on the play_prev button, we also define a new method:

def play_prev( ):
     prev_song  = listBox.curselection()
     prev_song = next_song[0] - 1
Enter fullscreen mode Exit fullscreen mode

Step 15

We want to get the song name of the prev_song and show it in the label:

prev_song_name = listBox.get(prev_song)
label.config(text = prev_song_name)
Enter fullscreen mode Exit fullscreen mode

Step 16

Next, we want to play the next song, to do this :

     mixer.music.load( rootpath + " \\ "  + prev_song_name)
      mixer.music.play( )
Enter fullscreen mode Exit fullscreen mode

Step 17

In this step, we want to hover from our selected song to our prev_song:

listBox.select_clear(0,'end')
listBox.activate(prev_song)
listen.select_set(prev_song) 
Enter fullscreen mode Exit fullscreen mode

Step 18

Next, we have to add this command to the prev button:

  prevButton = tk.Buttons(canvas, text = "Prev", image = prev_img, bg = 'black', borderwidth = 0, command = play_prev )
  prevButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 19

Next, we will work on the pause button by defining a new method:

def pause_song( ):
Enter fullscreen mode Exit fullscreen mode

Step 20

We have to write a condition to check the state of our song, so if the state of the song is paused we will play the song and if the song is playing then we pause the song and we will do this using a conditional statement:

def pause_song( ):
     if pauseButton["text"] == "Pause"
         mixer.music.pause()
     pauseButton["text"] = "Play"
     else:
          mixer.music.unpause()
          pauseButton["text"] = "Puse"
Enter fullscreen mode Exit fullscreen mode

Step 21

Lastly, we will add this command to the pause button:

pauseButton = tk.Buttons(canvas, text = "Pause", image = pause_img, bg = 'black', borderwidth = 0, command = pause_song )
  pauseButton.pack(pady = 15, in_ = top, side = 'left')
Enter fullscreen mode Exit fullscreen mode

Step 22

Finally, let's save and run our code to see our simple generated music player.

final image of our music player

Conclusion

Building a music player with Python can be an enjoyable journey for music lovers who want to dive into programming. Using Python and cool libraries like Tkinter and Pygame, you can make your personalized music player with a cool interface. It's important to set up your project environment properly to have all the tools and libraries you need in one place.

Creating a user-friendly interface is super important so that your music player looks great and is easy to use. Loading and showing music files, adding buttons, and creating playlists all help make your music player smooth to use. And don't forget the basics like play, pause, skip, and stop buttons to make sure your music player does its job well.

To sum it up, building this project lets you combine your passion for music with coding while learning how to create applications with Python. Follow these steps to create your music player, and you'll gain hands-on experience in coding, designing interfaces, and building working applications. Enjoy the creative process.

Top comments (0)