Build a Music Player Using Python.
Tags: webdev, beginners, programming, python
Published: 2024-04-20 14:17:54

##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](https://docs.python.org/3/library/tkinter.html) for the design, [pygame](https://pypi.org/project/pycopy-fnmatch/) for playing music, [os](https://www.tutorialsteacher.com/python/os-module) for handling files, and [fnmatch](https://pypi.org/project/pycopy-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](https://code.visualstudio.com/) (VS Code), create a new [Python](https://www.python.org/) 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](https://code.visualstudio.com/) and creating a new folder:


####Step 1

Open VS Code 


![vs code front page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvdu05dfq8kuevnvcwxz.png)




####Step 2

Create new folder


![image of a new vs code folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmh29m42xh2f2knym8y5.png)


####Step 3

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


![Image of vs code file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbtmy2ce7yrh4f4b1y46.png)




## 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](https://pypi.org/project/pygame/) in Python:

<prev>
```python
pip install pygame
```
</prev>


![Installed pygame library](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tzu717tp9tz7sltk7baw.png)




### Step 1

We will create this music player with Python using [Tkinter](https://docs.python.org/3/library/tkinter.html), [fnmatch](https://pypi.org/project/pycopy-fnmatch/), [os](https://www.tutorialsteacher.com/python/os-module) and [pygame](https://pypi.org/project/pygame/).

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

<prev>
```python
import tkinter as tk
import fnmatch
import os
from pygame import mixer 
```
</prev>

## 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()`:

<prev>
```python
canvas = tk.Tk( )
```
</prev>

### 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:

<prev>
```python
canvas.title("Music Player")
```
</prev>

### 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:

<prev>
```python
canvas.geometry(''600x800")
```
</prev>

### 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:

<prev>
```python
canvas.config(bg = 'black')
```
</prev>

### Step 5

Lastly, let's save and run our code:

<prev>
```python
canvas.mainloop( )
```
</prev>



![main window interface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8zwv6lglgtgy79n5bk5.png)



## 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:

<prev>
```python
rootpath = "C:\\Users\evane\Desktop\music"
```
</prev>

### 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:
<prev>
```python
pattern = "*.mp3"
```
</prev>

### 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`:

<prev>
```python
listBox = tk.Listbox( canvas, fg = "cyan", bg =    "black", width =  100, font = ('ds-digital', 14)) 
 listBox.pack (padx= 15, pady= 15)
```
</prev>

### 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`:
<prev>
```python
 for root, dirs, files in os.walk(rootpath) : 
      for filename in fnmatch.filter(files, pattern)
           listBox.index( 'end', filename )
```
</prev>

### 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.
](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnsu2vmfs11qsnirlexc.png)




## 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:
<prev>
```python
 Label = tk.Label(canvas, text = ' ', bg = 'black' fg = 'yelow', font = ('ds-digital', 18)
```
</prev>

### 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:

<prev>
```python
 Label = tk.Label(canvas, text = ' ', bg = 'black' fg = 'yelow', font = ('ds-digital', 18)
  Label.pack( pady = 15 )
```
</prev>

### 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:
<prev>
```python
  top = tk.Frame(canvas bg ="black")
  top.pack(padx = 10, pady = 5, anchor = 'center')
```
</prev>

### Step 4

Next We're adding a button called `prevButton` to allow users to skip to the previous song:
<prev>
```python
prevButton = tk.Buttons(canvas, text = "Prev") 
```
</prev>

### 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:
<prev>
```python
  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')
```
</prev>

### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9gf70w80ih4t6t1kxic.png)




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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yyd48i2bp52hq9idnu8s.png)




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

![Music icons in created python file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62krbs0kt3xn6y636xoi.png)



### Step 7

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

<prev>
```python
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 ")
```
</prev>

### 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:

<prev>
```python
  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')
```
</prev>

### Step 9

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



![Music icons in playlist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sfrs1f5qry50hpqdx4jf.png)



## 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:
<prev>
```python
 def select( ) :
```
</prev>
 
### 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:
<prev>
```python
 def select( ) :
     label.config(text = listBox.get("anchor"))
```
</prev>

### 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:
<prev>
```python
 def select( ) :
     label.config(text = listBox.get("anchor"))
     mixer.music.load( rootpath + " \\ "  + listBox.get("anchor"))
     mixer.music.play( )
```
</prev>

### Step 4

Next, we will initialize our mixer:
<prev>
```python
mixer.init ()
```
</prev>

### 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:

<prev>
```python
playButton = tk.Buttons(canvas, text = "Play", image = play_img, bg = 'black', borderwidth = 0, command = select )
  playButton.pack(pady = 15, in_ = top, side = 'left')
```
</prev>


### Step 6

We will define a new method called `stop()` that will stop the song that is currently playing:
<prev>
```python
def stop( ) :
     mixer.music.stop( )
```
</prev>

### 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:
<prev>
```python
 listBox.select_clear('active')
```
</prev>

### 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:
<prev>
```python
 stopButton = tk.Buttons(canvas, text = "Stop", image = stop_img, bg = 'black', borderwidth = 0, command = stop)
  stopButton.pack(pady = 15, in_ = top, side = 'left')
```
</prev>


### 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:
<prev>
```python
def play_next ( ):
     next_song  = listBox.curselection()
     next_song = next_song[0] +1
```
</prev>


### Step 10

To get the song name of the next song and update it in the label:
<prev>
```python
next_song_name = listBox.get(next_song)
label.config(text = next_song_name)
```
</prev>

### Step 11

Next, we need to play the next song also, to do this :
<prev>
```python
     mixer.music.load( rootpath + " \\ "  + next_song_name)
     mixer.music.play( ) 
```
</prev>

### 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:

<prev>
```python
listBox.select_clear(0,'end')
listBox.activate(next_song)
listen.select_set(next_song)
```
</prev>

### 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:
<prev>
```python
 nextButton = tk.Buttons(canvas, text = "Next", image = next_img, bg = 'black', borderwidth = 0, command = play_next)
  nextButton.pack(pady = 15, in_ = top, side = 'left')
```
</prev>


### Step 14

Next, we work on the `play_prev button`, we also define a new method:
<prev>
```python
def play_prev( ):
     prev_song  = listBox.curselection()
     prev_song = next_song[0] - 1
```
</prev>

### Step 15
We want to get the song name of the `prev_song` and show it in the label:

<prev>
```python
prev_song_name = listBox.get(prev_song)
label.config(text = prev_song_name)
```
</prev>

### Step 16

Next, we want to play the next song, to do this :
<prev>
```python
     mixer.music.load( rootpath + " \\ "  + prev_song_name)
      mixer.music.play( )
```
</prev>

### Step 17

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

<prev>
```python
listBox.select_clear(0,'end')
listBox.activate(prev_song)
listen.select_set(prev_song) 
```
</prev>

### Step 18

Next, we have to add this command to the prev button:
<prev>
```python
  prevButton = tk.Buttons(canvas, text = "Prev", image = prev_img, bg = 'black', borderwidth = 0, command = play_prev )
  prevButton.pack(pady = 15, in_ = top, side = 'left')
 ```
</prev>

### Step 19

Next, we will work on the pause button by defining a new method:
<prev>
```python
def pause_song( ):
```
</prev>
 
### 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:

<prev>
```python
def pause_song( ):
     if pauseButton["text"] == "Pause"
         mixer.music.pause()
     pauseButton["text"] = "Play"
     else:
          mixer.music.unpause()
          pauseButton["text"] = "Puse"
 ```
</prev>

### Step 21

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

<prev>
```python
pauseButton = tk.Buttons(canvas, text = "Pause", image = pause_img, bg = 'black', borderwidth = 0, command = pause_song )
  pauseButton.pack(pady = 15, in_ = top, side = 'left')
 ```
</prev>
### Step 22

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




![final image of our music player](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/154twkmm8ghilqk51an7.png)









##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.