Learn How to Create an MP3 Music Player in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Everybody loves listening music wouldn’t it be cool to have our very own mp3 music player. So, in this python project, we are going to create an mp3 player with the help of python and its libraries. Let’s start the python mp3 player project.

Python MP3 Music Player

We will create an mp3 music player in which we can play the song, pause it, resume it, and navigate from the current song to the next song as well as previous songs.

We will be using Python and its libraries. The first library that we will be using is Tkinter which is a widely used GUI library offered by python, we do not have to install it separately, as it comes with python itself.

Next, we will be using the mixer module of a very famous python library called Pygame.

Pygame is basically used to create video games, it includes computer graphics and sound libraries. Mixer is one such sound library. Then, we will use the os library of python to interact with the Operating system.

Project Prerequisites

To work on python mp3 player basic understanding of python programming language, tkinter, and mixer module of pygame would be helpful.

A basic understanding of Tkinter widgets would also be required, but don’t worry as we will be explaining every line of code as we go developing this mp3 player project.

Unlike the Tkinter library, we are required to install the Pygame library.

Please run following command in your command prompt or terminal to install pygame.

pip install pygame

Download Python MP3 Player Project

Please download the source code of Python mp3 player: MP3 Music Player Python Code

After doing this we are all set to start this Python project, you can use any IDE of your choice.

Steps to develop this project

  1. Import important libraries
  2. Create the project layout
  3. Define play, pause, and other music player functions

1. Import important libraries

#importing libraries 
from pygame import mixer
from tkinter import *
import tkinter.font as font
from tkinter import filedialog

Explanation:

  • First line imports the mixer module from pygame, then we import tkinter.
  • Next, we import the font module from the tkinter library. At last filedialog is imported which has many applications like opening a file, a directory, etc.

2. Create the overall layout of python mp3 player

#add many songs to the playlist
def addsongs():
    #a list of songs is returned 
    temp_song=filedialog.askopenfilenames(initialdir="Music/",title="Choose a song", filetypes=(("mp3 Files","*.mp3"),))
    #loop through everyitem in the list
    for s in temp_song:
        s=s.replace("C:/Users/lenovo/Desktop/DataFlair/Notepad/Music/","")
        songs_list.insert(END,s)
        
            
def deletesong():
    curr_song=songs_list.curselection()
    songs_list.delete(curr_song[0])
    
    
def Play():
    song=songs_list.get(ACTIVE)
    song=f'C:/Users/lenovo/Desktop/DataFlair/Notepad/Music/{song}'
    mixer.music.load(song)
    mixer.music.play()

#to pause the song 
def Pause():
    mixer.music.pause()

#to stop the  song 
def Stop():
    mixer.music.stop()
    songs_list.selection_clear(ACTIVE)

#to resume the song

def Resume():
    mixer.music.unpause()

#Function to navigate from the current song
def Previous():
    #to get the selected song index
    previous_one=songs_list.curselection()
    #to get the previous song index
    previous_one=previous_one[0]-1
    #to get the previous song
    temp2=songs_list.get(previous_one)
    temp2=f'C:/Users/lenovo/Desktop/DataFlair/Notepad/Music/{temp2}'
    mixer.music.load(temp2)
    mixer.music.play()
    songs_list.selection_clear(0,END)
    #activate new song
    songs_list.activate(previous_one)
    #set the next song
    songs_list.selection_set(previous_one)

def Next():
    #to get the selected song index
    next_one=songs_list.curselection()
    #to get the next song index
    next_one=next_one[0]+1
    #to get the next song 
    temp=songs_list.get(next_one)
    temp=f'C:/Users/lenovo/Desktop/DataFlair/Notepad/Music/{temp}'
    mixer.music.load(temp)
    mixer.music.play()
    songs_list.selection_clear(0,END)
    #activate newsong
    songs_list.activate(next_one)
     #set the next song
    songs_list.selection_set(next_one)

Explanation

  • Tk() is a top level widget that is used to create the main application window in which we will be building our python project.
  • The title() method is used to give a name to python mp3 player application which is displayed at the top.
  • mixer.init() is used to initialize the mixer module so that we can use it’s various functions in our application.
  • Listbox() widget is used to create a listbox in which we will store our songs.
    • We have passed various parameters, first is the root specifying that the widget should be placed in the python mp3 player window.
    • Then, bg is for background color, fg is for foreground color.
    • selectbackground and selectforeground basically change the background and the foreground color of a particular item upon selecting it.
  • grid() widget is a geometry manager which organizes the widgets properly in a grid-based fashion before placing it in the root window. columnspan=9 gives a space of 9 columns to our listbox widget.
  • Button() widget is used to create a button. We want the buttons in our main window so the input root is given. Then the text which will be displayed on the button is specified and at last in the command input a function is given which will be called when the button is clicked.
  • Menu() widget is displayed just under the title bar, it is used to conveniently access various operations. We are going to access Add songs and Delete songs for our playlist, upon clicking addsongs and deletesong functions are called respectively.

3. Create music player functions

#creating the root window 
root=Tk()
root.title('DataFlair Music player App ')
#initialize mixer 
mixer.init()

#create the listbox to contain songs
songs_list=Listbox(root,selectmode=SINGLE,bg="black",fg="white",font=('arial',15),height=12,width=47,selectbackground="gray",selectforeground="black")
songs_list.grid(columnspan=9)

#font is defined which is to be used for the button font 
defined_font = font.Font(family='Helvetica')

#play button
play_button=Button(root,text="Play",width =7,command=Play)
play_button['font']=defined_font
play_button.grid(row=1,column=0)

#pause button 
pause_button=Button(root,text="Pause",width =7,command=Pause)
pause_button['font']=defined_font
pause_button.grid(row=1,column=1)

#stop button
stop_button=Button(root,text="Stop",width =7,command=Stop)
stop_button['font']=defined_font
stop_button.grid(row=1,column=2)

#resume button
Resume_button=Button(root,text="Resume",width =7,command=Resume)
Resume_button['font']=defined_font
Resume_button.grid(row=1,column=3)

#previous button
previous_button=Button(root,text="Prev",width =7,command=Previous)
previous_button['font']=defined_font
previous_button.grid(row=1,column=4)

#nextbutton
next_button=Button(root,text="Next",width =7,command=Next)
next_button['font']=defined_font
next_button.grid(row=1,column=5)

#menu 
my_menu=Menu(root)
root.config(menu=my_menu)
add_song_menu=Menu(my_menu)
my_menu.add_cascade(label="Menu",menu=add_song_menu)
add_song_menu.add_command(label="Add songs",command=addsongs)
add_song_menu.add_command(label="Delete song",command=deletesong)


mainloop()

Explanation

  • addsongs() is used to add songs in our listbox, filedialog.askopenfilenames() opens a dialog box corresponding to the folder whose path is provided. Then, we can select songs and store them in temp_song variable, after this we loop through the list to insert every item in the listbox.
  • deletesong() is used to delete a selected song, songs_list.curselection() function returns a tuple in which the first element is the index of the selected song. Then, .delete() function is used to delete the song corresponding to the index which is passed.
  • Play() function is used to play the selected song , we use the .get() method to get the selected song, then we load the song and play it using the next two lines.
  • Pause() function is used to pause the song, we do not need to pass any argument to the mixer.music.pause() function.
  • Stop() function is used to stop the song, we use mixer.music.stop() function to stop the song.
    songs_list.selection_clear(ACTIVE) is used to unselect the selected song from the listbox
  • Resume() function is used to resume the song using mixer.music.unpause() function.
  • Previous() function is used to play the previous song in the listbox, songs_list.curselection() function returns a tuple in which the first element is the index of the selected song in python mp3 music player project. We store it in a variable called previous_one, then we update its value to get the previous index by subtracting 1. Next, songs_list.get(previous_one) returns the previous song, we store this value in temp2 after that we load this song and play it.
    We would face a problem here, although the previous song would start playing but the selected song would not change. So, we rectify that with the help of the next three lines of code.
  • Next() function is implemented in a similar way as the previous function. Here, instead of subtracting 1, we add 1 apart from this step every other step is the same.

Python MP3 Music Player Output

python mp3 player output

Summary

Congratulations! We have successfully created python mp3 music player, now we don’t have to rely on any other app.

Through this python project we learned a lot of things about python and its libraries, the first one being the Tkinter library, a widely-used GUI library and various widgets that it offers, then the important mixer module of the pygame library which is used to manipulate the music.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

18 Responses

  1. Ayush says:

    Code is not running.

    • Satyajit Das says:

      Hi, Ayush. I am getting the below error, kindly help me please.

      File “song_player_recorder.py”, line 15, in addsongs
      songs_list.insert(END,s)
      NameError: name ‘songs_list’ is not defined

      Where to define songs_list ? can you give hint plz

      Thanks.

    • DataFlair Team says:

      We have made necessary changes in our code and the mp3 player is running successfully. Kindly review and rerun the code.

  2. Fernando says:

    Code works. You just need to change the directory path to match yours.

  3. Tapish Sharma says:

    How can i change code to open the music files to add songs. The add songs command is not working.

  4. Satyajit Das says:

    Hi, Data Flair I am getting the below error, kindly help me please.

    File “song_player_recorder.py”, line 15, in addsongs
    songs_list.insert(END,s)
    NameError: name ‘songs_list’ is not defined

    Thanks.

  5. Prikshit Sharma says:

    temp_song not defined in for s in temp_song:

    please reply asap

  6. Prikshit Sharma says:

    now add songs command not working
    please reply asap
    pleasse help
    please

  7. Prikshit Sharma says:

    now add songs command not working

  8. ABHAY NEERAJ KHALKHO says:

    Abhay

  9. YourHelper says:

    I did some changes and for me, its runing

    # Required : tkinter, pygame
    from pygame import mixer
    from tkinter import *
    import tkinter.font as font
    from tkinter import filedialog
    import sys

    # Functions
    def addsongs():
    tmp_song = filedialog.askopenfilename(initialdir=”Music/”, title=”Choose a Song”,
    filetypes=((“mp3 Files”, “*.mp3″),))
    chain = ”
    for song in tmp_song:
    song = song.replace(f”{sys.argv[0][:-3]}/Music”,””)
    chain += song
    song_add = chain
    song_list.insert(END, song_add)

    def delsong():
    curr_song = song_list.curselection()
    song_list.delete(curr_song[0])

    def Play():
    song = song_list.get(ACTIVE)
    #song = f”{sys.argv[0][:-3]}/Music/{song}”
    mixer.music.load(song)
    mixer.music.play()

    def Pause():
    mixer.music.pause()

    def Stop():
    mixer.music.stop()
    song_list.select_clear(ACTIVE)

    def Resume():
    mixer.music.unpause()

    def Previous():
    prev_one = song_list.curselection()
    prev_one = prev_one[0] -1
    tmp2 = song_list.get(prev_one)
    tmp2 = f”{sys.argv[0][:-3]}/{tmp2}”
    mixer.music.load(tmp2)
    mixer.music.play()
    song_list.selection_clear(0, END)
    song_list.activate(prev_one)
    song_list.selection_set(prev_one)

    def Next():
    next_one = song_list.curselection()
    next_one = next_one[0] +1
    tmp = song_list.get(next_one)
    tmp = f”{sys.argv[0][:-3]}/{tmp}”
    mixer.music.load(tmp)
    mixer.music.play()
    song_list.selection_clear(0, END)
    song_list.activate(next_one)
    song_list.selection_set(next_one)

    # Root window
    root = Tk()
    root.title(‘Music Player MP3′)

    # Init mixer
    mixer.init()

    # Listbox
    song_list = Listbox(root,
    selectmode=SINGLE,
    bg=’black’,
    fg=’red’,
    font=(‘arial’, 15),
    height=15,
    width=50,
    selectbackground=’gray’,
    selectforeground=’red’)
    song_list.grid(columnspan=10)

    # Button font
    button_font = font.Font(family=’Helvetica’)

    # Play button
    play_button = Button(root,
    text=”Play”,
    width=7,
    command=Play)
    play_button[‘font’] = button_font
    play_button.grid(row=1,
    column=0)

    # Pause button
    pause_button = Button(root,
    text=”Pause”,
    width=7,
    command=Pause)
    pause_button[‘font’] = button_font
    pause_button.grid(row=1,
    column=1)

    # Stop button
    stop_button = Button(root,
    text=”Stop”,
    width=7,
    command=Stop)
    stop_button[‘font’] = button_font
    stop_button.grid(row=1,
    column=2)
    # Resume button
    resume_button = Button(root,
    text=”Resume”,
    width=7,
    command=Resume)
    resume_button[‘font’] = button_font
    resume_button.grid(row=1,
    column=3)

    # Previous button
    previous_button = Button(root,
    text=”Prev”,
    width=7,
    command=Previous)
    previous_button[‘font’] = button_font
    previous_button.grid(row=1,
    column=4)

    # Next button
    next_button = Button(root,
    text=”Next”,
    width=7,
    command=Next)
    next_button[‘font’] = button_font
    next_button.grid(row=1,
    column=5)

    # Menu
    main_menu = Menu(root)
    root.config(menu=main_menu)
    add_song = Menu(main_menu)
    main_menu.add_cascade(label=’Menu’, menu=add_song)
    add_song.add_command(label=”Add Song”, command=addsongs)
    add_song.add_command(label=”Delete Song”, command=delsong)

    mainloop()

  10. Anurag Rawat says:

    prev and next button not working.Its throwing Index out of range error

  11. OneMadGypsy says:

    This code is not very good. You are importing tkinter with star which is bad practice. You don’t have an `if __name__ == __main__:` clause at the end of your script. I’m not really sure why you capitalized the first letter of every function, against convention. Everywhere you change the song the pygame mixer should be unloaded. Why do you have your directory paths hardcoded into the script? Having a pause and resume button is pretty silly. You could just toggle the play button to also act as pause, and get rid of the pause and resume buttons. Why do you have `columnspan=9` on `song_list` when the whole app is only 6 columns wide? The `font` and `width` are identical across your buttons so you could have just made those settings a `dict` and used it in the button constructors as `**kwargs`. Your `Previous` and `Next` functions are identical except for the direction they work in so, the truly identical parts should probably be their own function and `Previous/Next` just primes the direction that the shared function works in.

Leave a Reply

Your email address will not be published. Required fields are marked *