Как написать свой плеер на питоне

Cover image for Make your own music player in python

The original article can be found at kalebujordan.dev

Make your own python music player

In this tutorial, you’re going to learn how to make your own MP3 Music Player in Python using pygame and Tkinter libraries which is able to load, play, pause, and stop the music.

Requirements

To be able to follow this tutorial you need to have Tkinter and pygame installed on your machine

Installation

  • Linux
sudo apt-get install python3-tk

pip3 install pygame

Enter fullscreen mode

Exit fullscreen mode

  • Window
pip install pygame

Enter fullscreen mode

Exit fullscreen mode

Now once everything is ready Installed, we now ready to begin coding our very own music player

Let’s get started

We gonna use Tkinter to render our application menu and buttons, and also loading the music from files and then pygame library to play, pause and stop the music

Basics of pygame

Pygame has an inbuilt method called mixer () which provides us intuitive syntax on dealing with sounds files in python, we will see ;

  • loading and playing music
  • pausing and unpausing music
  • stoping the music file

loading and playing music with pygame

To play music with pygame you’re firstly supposed to import mixer(), initialize it through init(), *and then using *music.load() to load the music and finally playing it with music.play().

Example of usage

from pygame import mixer

mixer.init() #Initialzing pyamge mixer

mixer.music.load.('filename.mp3') #Loading Music File

mixer.music.play() #Playing Music with Pygame

Enter fullscreen mode

Exit fullscreen mode

Pausing and unpausing music with pygame.

use* music.pause() and music.unpause()* to pause and unpause your music, but make your music file is loaded first before using these methods.

Example of usage

mixer.music.pause() #pausing music file

mixer.music.unpause() #unpausing music file

Enter fullscreen mode

Exit fullscreen mode

Stop a music file

use music.stop() to stop your music completely from playing, once you use this method the loaded music will be cleared in pygame memory.

mixer.music.stop()

Enter fullscreen mode

Exit fullscreen mode

Building your music player exoskeleton

We have already covered the basics of playing music with python, now it’s time to begin designing our application user interface{UI) and then link together with the logics.

First Let us import all necessary Library

from tkinter import *

from tkinter import filedialog

from pygame import mixer

Enter fullscreen mode

Exit fullscreen mode

Let’s now implement our class & Buttons for our application

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False

Enter fullscreen mode

Exit fullscreen mode

Let’s now add the method to the class we just made to load music file from our computer, just as shown in the code below

Adding Load Method to our MusicPlayer class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()

Enter fullscreen mode

Exit fullscreen mode

After Loading the Music file from the file we need a function to Play our Music File, Let’s make it using the concepts we just learned above.

Adding Play Method to our class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()

Enter fullscreen mode

Exit fullscreen mode

After adding the Play Method to our class we need a Method to pause and unpause & also to Stop the Music

Finally Let’s add the pause and stop method to our class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()

Enter fullscreen mode

Exit fullscreen mode

Let’s look at our Final will app (app.py)

from tkinter import *
from tkinter import filedialog
from pygame import mixer

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) 
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()
root = Tk()
app= MusicPlayer(root)
root.mainloop()

Enter fullscreen mode

Exit fullscreen mode

Output

If you run the above code the output will be as shown below, now you can play around with it by loading, playing, pausing, and stopping the music, full demo in youtube link at the end of the article.

View demo on youtube

Based on your interest I recommend you to also check these;

  • How to make a digital clock in Python
  • How to track phone number in Python
  • How to make a python GUI calculator in Python
  • How to program Arduino board with Python
  • How to build a website blocker in Python

In case of any comment,suggestion or difficulties drop it on the comment box below, and then I will get back to you ASAP.

GitHub logo

Kalebu
/
MusicPlayer

A music player application made with python for learning purpose

MusicPlayer

Simple Basic Player implemented in Python using Tkinter & Pygame Library

Music Player Application Python Project

Everyone enjoys listening to music, therefore wouldn’t it be great to have our own MP3 player? So, in this python project, we’re going to use python and its libraries to make an mp3 player. Let’s get started on the mp3 player in Python project.

MP3 Music Player Application in Python Language

We’ll make an mp3 music player that allows us to play, stop, and restart tracks, as well as move from one song to the next and previous ones.

Python and associated libraries will be used. The first package we’ll use is Tkinter, a widely used GUI toolkit provided by Python. We don’t need to install it separately since it’s included with Python.

The mixer module of Pygame, a well-known Python library, will be used next.

Pygame is a programming language that is used to develop video games and contains graphics and sound libraries. One such sound library is Mixer. Then, to interface with the operating system, we’ll utilize Python’s os package.

Prerequisites for the Project

Working on a python mp3 player requires a basic familiarity of the Python programming language, tkinter, and the Pygame mixer module.

A basic grasp of Tkinter widgets is also necessary, but don’t worry, we’ll go through every line of code as we build this mp3 player project.

Unlike the Tkinter library, the Pygame library must be installed.

To install pygame, use the following line in your command prompt or terminal.

pip install pygame

Steps to take in order to complete this project

  • Import essential libraries
  • Make a project layout.
  • Define the functionality of the music player, such as play, pause, and other options.

Source Code for MP3 Music Player Application

#importing libraries 
from pygame import mixer
from tkinter import *
import tkinter.font as font
from tkinter import filedialog
#creating the root window 
root=Tk()
root.title('DataFlair Python MP3 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()
#add many songs to the playlist of python mp3 player
def addsongs():
    #to open a file  
    temp_song=filedialog.askopenfilenames(initialdir="Music/",title="Choose a song", filetypes=(("mp3 Files","*.mp3"),))
    ##loop through every item in the list to insert in the listbox
for s in temp_song:
        s=s.replace("C:/Users/DataFlair/python-mp3-music-player/","")
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/DataFlair/python-mp3-music-player/{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/DataFlair/python-mp3-music-player/{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)

Output

Music plaayer python application

Summary

Congratulations! We have successfully developed a python mp3 music player, and we no longer need to depend on any other application.

We learnt a lot about python and its libraries via this project, the first of which was the Tkinter library, which is a widely-used GUI library with a variety of widgets, and then the essential mixer module of the pygame library, which is used to alter the music.

Music Player Application Python Project

Everyone enjoys listening to music, therefore wouldn’t it be great to have our own MP3 player? So, in this python project, we’re going to use python and its libraries to make an mp3 player. Let’s get started on the mp3 player in Python project.

MP3 Music Player Application in Python Language

We’ll make an mp3 music player that allows us to play, stop, and restart tracks, as well as move from one song to the next and previous ones.

Python and associated libraries will be used. The first package we’ll use is Tkinter, a widely used GUI toolkit provided by Python. We don’t need to install it separately since it’s included with Python.

The mixer module of Pygame, a well-known Python library, will be used next.

Pygame is a programming language that is used to develop video games and contains graphics and sound libraries. One such sound library is Mixer. Then, to interface with the operating system, we’ll utilize Python’s os package.

Prerequisites for the Project

Working on a python mp3 player requires a basic familiarity of the Python programming language, tkinter, and the Pygame mixer module.

A basic grasp of Tkinter widgets is also necessary, but don’t worry, we’ll go through every line of code as we build this mp3 player project.

Unlike the Tkinter library, the Pygame library must be installed.

To install pygame, use the following line in your command prompt or terminal.

pip install pygame

Steps to take in order to complete this project

  • Import essential libraries
  • Make a project layout.
  • Define the functionality of the music player, such as play, pause, and other options.

Source Code for MP3 Music Player Application

#importing libraries 
from pygame import mixer
from tkinter import *
import tkinter.font as font
from tkinter import filedialog
#creating the root window 
root=Tk()
root.title('DataFlair Python MP3 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()
#add many songs to the playlist of python mp3 player
def addsongs():
    #to open a file  
    temp_song=filedialog.askopenfilenames(initialdir="Music/",title="Choose a song", filetypes=(("mp3 Files","*.mp3"),))
    ##loop through every item in the list to insert in the listbox
for s in temp_song:
        s=s.replace("C:/Users/DataFlair/python-mp3-music-player/","")
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/DataFlair/python-mp3-music-player/{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/DataFlair/python-mp3-music-player/{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)

Output

Music plaayer python application

Summary

Congratulations! We have successfully developed a python mp3 music player, and we no longer need to depend on any other application.

We learnt a lot about python and its libraries via this project, the first of which was the Tkinter library, which is a widely-used GUI library with a variety of widgets, and then the essential mixer module of the pygame library, which is used to alter the music.

Время на прочтение
3 мин

Количество просмотров 6.2K

Hello

world

, %Username%. Я заметил, что в последнее на Хабре время достаточно много постов про python. Да, язык набирает популярность. Ура товарищи! Вот и я решил приобщиться к этому языку. Достаточо скоро надоело хэлловорлдить и захотелось мне написать что то нужное.Лирическое отстпуление: Перешел с win на ubuntu(Знаю, что попса, но ради дела, а не понта делается) и понял, что нет приемлимого аудиопроигрывателя в моем поле зрения, все проигрыватели предлагали либо выглядели не приятно, либо были слишком тяжелыми. Немного поленившись я взялся за дело.

Уже в самом начале написания скрипта встал перед выбором. Использовать pyqt и библиотеку для работы со звуком, либо использовать pygame. Выбрал второе, об этом очень пожалел. Процесс начался. Полный код выкладывать сюда не буду, он ждет вас по ссылке
Однако в связи с ужаснейшей привычкой не комментировать код я выделю здесь основные моменты работы с pygame.

Концепция заключается в том, что в программе существует главный цикл, в котором идет обработка информации и изменение условно говоря Картинки на экране.

while running:

pygame.display.init()
pygame.font.init()
pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=4096)

Инициализация используемых модулей.
Вообще по идее можно было все это заменить на pygame.init(), но так выглядит солиднее, да и внутренний параноик будет немного меньше беспокоиться о быстродействии. Так же нужно разъяснить последнюю строчку
frequency=44100 — Частота дискретизации звука, по умолчанию 22050(Звук ужасный)
size = -16 — Страшная магия вуду, буду благодарен, если кто-то разъяснит для чего нужен этот параметр.
channels = 2 — Указываем количество каналов для воспроизведения
buffer=4096 — Размер буфера

pygame.mixer.music.set_volume(self.logic.volume)
Указываем громкость воспроизведения. Важно, стоит помнить, что этим методом указывается громкость всей программы, а не отдельных файлов.

self.screen = pygame.display.set_mode((600,230))

Этот метод создает главное окно и главный Surface. Как вы уже догадались он принимает как аргумент — разрешение будущего окна.

pygame.display.set_caption(u"Ktulhu fhtang")

Указание заголовка главного окна.

self.ui = pygame.font.Font("Arial.ttf",32)

Загрузка нового шрифта из файла. Загружать из файла не обязательно, но мне кажется это немного более простым, нежели запарка с sysFont.
Как аргументы принимает название файла и размер шрифта.

self.ui.render(u"Play",True,(0,0,0))

С помощью этого метода отрисовывается полученный первым аргументом текст. Второй аргумент — Сглаживание текста. Третьим аргументом принимается значения цвета в формате (r,g,b). Сразу стоит отметить, что pygame может отрисовывать unicode, если поставить волшебную букву u»»

self.screen.fill((255,255,255))

Закрашивает экран указаным цветом, вообще не только экран, а любой Surface, примитивы в том числе.

self.screen.blit(self.play,(0,0))

Крайне важный метод blit, он принимает 2 аргумента. 1 — Любой Surface объект, 2 — Координаты в которых нужно отрисовать слой. Что же делает это метод? Он Присоединяет принимаемый surface к surface к которому он применяется. В данном случае self.play присоединяется к основному surface.

event = pygame.event.poll()

Сохраняем в переменную все события собранные за один прогон цикла.

pygame.display.flip()

Метод обновляющий изображение на экране. Без него вы не увидите ничего кроме черного экрана

pygame.time.wait(25)

В связи с тем, что python не слишком быстрый язык высокой количество fps сильно нагружает даже мощные компьютеры, поэтому каждый прогон цикла я заставляю ждать 25 миллисекунд. FPS не замерял, но процессор не нагружается, а скорости отрисовки хватает.

Почему же я пожалел, что выбрал pygame? Вся проблема в том, что при попытке воспроизведения mp3 файлов с тегами версии 3(а таких уже очень много) pygame виснет и это крайне не приятно. Единственным выходом является смена библиотеки, не знаю когда сей баг пофиксят.

rghost.ru/38700690 — Вот Франкинштейн описаный в статье выше.

Знаю код не претендует на звание самого логичного и хорошо оформленного, но все же прошу не пинать

Hello friends how are you, Today in this post «Music player in python» i am going to teach you how you can create an Audio/Music player in python. If you are a computer science students then this may be a small project for you and you can submit this into your school or college. 

In this music player you will get a button for Play Stop Pause Rewind Volume/Sound and Mute.   

Now  i am going to explain it step by step so just go through this post to understand this completely.

Step 1: Install Python and Pycharm : Open any browser and type Download Python and click the first link you will get official website of python here you will get a Download button and after clicking on this button you will get exe of latest python version just install it into your system.

To install Pycharm IDE Open any browser and type Download Pycharm and click the first link you will get official website of Pycharm  here you will get a black download button and after clicking on this button you will get exe of Pycharm   just install it into your system. If you are facing problem to install then watch this video TEXT TO SPEECH IN PYTHON in which i have explained step by step.

Step 2: Create Project : Open Pycharm and click on new project, you will get a new screen in which you have to select directory name and after directory name type a project name like «MusicPlayer» and then click on create button.

Now its time to create python file inside project. Right click on project name «MusicPlayer» and select new and then click on Python file , you will get a popup screen in which you have to type a name for python file here just type music for the name for python file.

Here I have explained how to create project and python file in very short because i have already explained it in this video TEXT TO SPEECH IN PYTHON so click this if you are facing problem to create project in Pycharm.

Step 3: Install libraries: Before doing code for this we have to first, install the library which is used to convert text into speech. To install this library click on terminal which will be in left bottom of screen.We have to install the following libraries to make music player.

  • pygame
  • ttkthemes    
  • mutagen
  • time

To install these libraries click on terminal which will be in left bottom of project screen. For better understanding see the below screenshot

Music player in python

After click, a console screen will open in which you have to type pip install pygame and press enter after typing. For better understanding see the below screenshot.

Music player in python

Now wait for some second you will get a message like installed successfully. Now you have to install the following libraries one by one which is given below.

pip install pygame
pip install ttkthemes
pip install mutagen
pip install time

If you will get an error then click this video Link TEXT TO SPEECH IN PYTHON here i have already explained how you can solve this type of error.

Step 4: Write Python code:  Now i am going to write the complete code of this project , open the music.py file and just copy this code and paste it.

"""
Krazyprogrammer Presents Music Player
"""
from tkinter import filedialog
from tkinter import ttk
import tkinter.messagebox
from tkinter import *
import os
import threading
from ttkthemes import themed_tk as tk
from mutagen.mp3 import MP3
import time
from pygame import mixer

root = tk.ThemedTk()
#root.geometry("555x290")
root["bg"]="#195FBA"
#setting theme for player
root.set_theme("elegance")
statusbar = ttk.Label(root, text="Welcome to Krazy Music Player", anchor=W, font='Arial 8 italic')
statusbar.pack(side=BOTTOM, fill=X)
statusbar1 = ttk.Label(root, text="Welcome to Krazy Music Player", anchor=W, font='Arial 8 italic')
statusbar1.pack(side=TOP, fill=X)
#// Create the menubar
menubar = Menu(root)
root.config(menu=menubar)
#// Create the submenu
subMenu = Menu(menubar, tearoff=0)
#list for storing play
songplaylist = []
def browse_file():
    global filename_path
    filename_path = filedialog.askopenfilename()
    add_to_songplaylist(filename_path)
    mixer.music.queue(filename_path)
def add_to_songplaylist(filename):
    filename = os.path.basename(filename)
    index = 0
    songplaylistcontainer.insert(index, filename)
    songplaylist.insert(index, filename_path)
    index += 1
menubar.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Open", command=browse_file)
subMenu.add_command(label="Exit", command=root.destroy)
mixer.init()  #// initializing the mixer
root.title("Krazy Music Player")
ltframe = Frame(root,bg="#364C69")
ltframe.pack(side=LEFT, padx=30, pady=30)
songplaylistcontainer = Listbox(ltframe,fg='white')
songplaylistcontainer["bg"]="#364C69"
songplaylistcontainer.pack()
addBtn = ttk.Button(ltframe, text="+ Add",command=browse_file)
addBtn.pack(side=LEFT)
def remove_song():
    sel_song = songplaylistcontainer.curselection()
    sel_song = int(sel_song[0])
    songplaylistcontainer.delete(sel_song)
    songplaylist.pop(sel_song)
root.style = ttk.Style()
root.style.theme_use("clam")
remBtn = ttk.Button(ltframe, text="- Del", command=remove_song)
remBtn.pack(side=LEFT)
root.style.configure('TButton', background='#12936F')
rtframe = Frame(root,bg="#364C69")
rtframe.pack(pady=30,padx=20)
topframe = Frame(rtframe,bg="#364C69")
topframe.pack()
root.style = ttk.Style()
#root.style.theme_use("clam")
root.style.configure('TLabel', background='#364C69')
lengthlabel = ttk.Label(topframe,text='Total Time : --:--')
lengthlabel.pack(pady=5)
currenttimelabel = ttk.Label(topframe, text='Current Time : --:--')
currenttimelabel.pack()
def show_details(play_song):
    file_data = os.path.splitext(play_song)
    if file_data[1] == '.mp3':
        audio = MP3(play_song)
        total_length = audio.info.length
    else:
        a = mixer.Sound(play_song)
        total_length = a.get_length()
    mins, secs = divmod(total_length, 60)
    mins = round(mins)
    secs = round(secs)
    timeformat = '{:02d}:{:02d}'.format(mins, secs)
    lengthlabel['text'] = "Total Time" + ' - ' + timeformat
    t1 = threading.Thread(target=start_count, args=(total_length,))
    t1.start()
def start_count(t):
    global paused
    current_time = 0
    while current_time <= t and mixer.music.get_busy():
        if paused:
            continue
        else:
            mins, secs = divmod(current_time, 60)
            mins = round(mins)
            secs = round(secs)
            timeformat = '{:02d}:{:02d}'.format(mins, secs)
            currenttimelabel['text'] = "Current Time" + ' - ' + timeformat
            time.sleep(1)
            current_time += 1
def play_music():
    global paused
    if paused:
        mixer.music.unpause()
        statusbar['text'] = "Music Resumed"
        paused = FALSE
    else:
        try:
            stop_music()
            time.sleep(1)
            sel_song = songplaylistcontainer.curselection()
            sel_song = int(sel_song[0])
            play_it = songplaylist[sel_song]
            mixer.music.load(play_it)
            mixer.music.play()
            statusbar['text'] = "Playing music" + ' - ' + os.path.basename(play_it)
            show_details(play_it)
        except:
            tkinter.messagebox.showerror('File not found', 'Krazy music player could not find the file. Please select again.')
def stop_music():
    mixer.music.stop()
    statusbar['text'] = "Music Stopped"
paused = FALSE
def pause_music():
    global paused
    paused = TRUE
    mixer.music.pause()
    statusbar['text'] = "Music Paused"
def rewind_music():
    play_music()
    statusbar['text'] = "Music Rewinded"
def set_vol(val):
    volume = float(val) / 100
    mixer.music.set_volume(volume)
muted = FALSE
def mute_music():
    global muted
    if muted:
        mixer.music.set_volume(0.7)
        volumeBtn.configure(text="Mute")
        scale.set(70)
        muted = FALSE
    else:
        mixer.music.set_volume(0)
        volumeBtn.configure(text="Volume")
        scale.set(0)
        muted = TRUE
middleframe = Frame(rtframe,bg="#364C69")
middleframe.pack(pady=30, padx=30)
playBtn = ttk.Button(middleframe, text="Play", command=play_music)
playBtn.grid(row=0, column=0, padx=10)
stopBtn = ttk.Button(middleframe, text="Stop", command=stop_music)
stopBtn.grid(row=0, column=1, padx=10)
pauseBtn = ttk.Button(middleframe, text="Pause", command=pause_music)
pauseBtn.grid(row=0, column=2, padx=10)
bottomframe = Frame(rtframe,bg="gray")
bottomframe.pack(pady=10,padx=5)
rewindBtn = ttk.Button(bottomframe, text="Rewind", command=rewind_music)
rewindBtn.grid(row=0, column=0,padx=10)
volumeBtn = ttk.Button(bottomframe, text="Mute", command=mute_music)
volumeBtn.grid(row=0, column=1)
scale = ttk.Scale(bottomframe, from_=0, to=100, orient=HORIZONTAL, command=set_vol)
scale.set(70)  # implement the default value of scale when music player starts
mixer.music.set_volume(0.7)
scale.grid(row=0, column=2, pady=15, padx=30)
def on_closing():
    stop_music()
    root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
if __name__==mainloop():
 root.mainloop()

Here just copy this code and paste it into music.py file.

Step 5: Run Code: Now its time to execute this code just right click on the coding section and click on Run Program

Music player in python

When you will run this code then you will get a Music Player like below.

Music player in python

Here in this Music Player you can add many mp3 songs into list by clicking on Add button.

if you want to play any song of the list then click on song name to select and then click on play button.

I hope now you can  create  «Music player in python«. If you have any doubt regarding this post  or you want something more in this post then let me know by comment below i will work on it definitely.

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 

If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. Try to learn something new and teach something new to other. 

If you like my post then share it with your friends. Thanks😊Happy Coding.

The media player is in dark theme with all the functionalities of a modern media player we can adjust the volume from the player switch back and front to previous and next songs. We can shuffle our playlist and also can move the song to any position as we want using the song slider.

Which Packages Used for create own Mp3 music player using python

from tkinter import *
import tkinter.ttk as ttk
import pygame
import os
from PIL import ImageTk,Image
import random
from tkinter import filedialog
import time
from mutagen.mp3 import MP3

The Above packages are used to make the make the Media Player

i. tkinter for using Gui in python
ii. tkinter.ttk for using Slider for volume and song track
iii. pygame used for sound libraries
iv. os module for importing songs from file
v. PIL module used for images
vi. Random module used for shuffling playlist
vii. Filedialog used for adding more songs in the player directly
viii. Time module used for tracking song sound
ix. Mutagen used to get the song length

Tk() function is used to initialize the root window. The root window is a main application window in our programs.

Initial after calling all the packages a class My_music_player() is created and in the class a class constructor is created to initialise:

The use of the constructor is given below

i. Initializing Root window
ii. Title of the player
iii. Icon (bitmap)
iv. Dimension(geometry) of the player
v. Initialised pygame and pygame mixer
vi. Variables declared for track and status
vii. Root.root.resizable(0, 0) function is called to prevent resizing of window
viii. Global variables are declared to use in the player
ix. Initializing variables to use it further as accordingly

Media player title and Icon

Play Frame is created to group the control keys of the player.
All the control keys in the player comes under this frame. Control keys include Stop Button, Previous Button, Play and Pause Button,Shuffle Button and Button for hiding the Playlist.

Control Keys for MP3 player in python

All the Buttons are Assigned their respective functions using command attribute. The functionalities are stop button for stopping the music, Previous and Next Button for Previous and next songs, Play and Pause Button for playing and pausing the musing, shuffle button is also included to shuffle the play list.
The button keys are made using icon and Font Awesome 5 font.
The play pause button chances according to the playing and pausing of music

Change in Play Pause Button in python

Buttons and Lables of Tkinter module is used to create the control key in the play frame.

Playerarea Frame is created to show the player area where Image is show for better looks.
Song slider and volume controls are given in this frame.
Song Description and status of the song is also included in this frame.
The duration of the song and time elapsed is also shown in this frame.

Volume control functions in MP3 player in python
The symbol of the volume icon changes on increasing and decreasing of the volume and mute and unmute the volume.
Volume can be adjusted using the slider scrolling up and down
Ttk.scale() is used to create the volume slider.

Functions and attributes of Pygame module are use to adjust and set the volume using the slider

We can move the song to any position as we want using the song slider.
The Description area shows the Name of the song currently Playing and also the status of the song i.e. Playing, Paused or Stopped.

Add Button in MP3 player in python

Add Button is also included to add song to the player directly form the computer we can select multiple files also at once. The songs are added at the end of the playlist.

The Player Frame with above mentioned fuctionalities

how to make your own MP3 music player in python using Tkinter
how to make your own MP3 music player in python using Tkinter

The third Frame used in this media player is song_list Frame.
This frame is used for the playlist of the media player.
Listbox of tkinter is used for the playlist.
Scrolling option on the right side of the playlist is enabled for scrolling along y axis to access songs in the playlist.

Double click functionality is enables on the listbox to play the selected song.
Song can also be played using tha play button after selecting the song by clicking once.
Bind() is use to bind the mouse click for playing songs.

Functions of OS modules are used to fetch the song from the song folder.
Song can also be added using the add button.

Many function are created to do task according to the button press from the control area. The functions include function to add song, function to manage double click and playing the song, function to adjust volume, Functions for play and pause music and start and stop music, function to hide playlist, function to shuffle the playlist, functions to mute and unmute.
Functionalities for previous and next songs.and slider functions.

The whole media player looks like this

how to make your own MP3 music player in python using Tkinter

how to make your own MP3 music player in python using Tkinter

Source Coding For Create Mp3 music player in python :

We need to First import all necessary Library

from tkinter import *
from tkinter import filedialog
from pygame import mixer

Create class & Buttons for our application

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False

Adding Load Method to our MusicPlayer class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()

Adding Play Method to our class

class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
After adding Play Method to our class we need a Method to pause and unpause & also to stop the Music

Finally Let’s add pause and stop method to our class
Python
class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60)
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()
​

look at our Final will app (app.py)

from tkinter import *
from tkinter import filedialog
from pygame import mixer
​
class MusicPlayer:
    def __init__(self, window ):
        window.geometry('320x100'); window.title('Iris Player'); window.resizable(0,0)
        Load = Button(window, text = 'Load',  width = 10, font = ('Times', 10), command = self.load)
        Play = Button(window, text = 'Play',  width = 10,font = ('Times', 10), command = self.play)
        Pause = Button(window,text = 'Pause',  width = 10, font = ('Times', 10), command = self.pause)
        Stop = Button(window ,text = 'Stop',  width = 10, font = ('Times', 10), command = self.stop)
        Load.place(x=0,y=20);Play.place(x=110,y=20);Pause.place(x=220,y=20);Stop.place(x=110,y=60) 
        self.music_file = False
        self.playing_state = False
    def load(self):
        self.music_file = filedialog.askopenfilename()
    def play(self):
        if self.music_file:
            mixer.init()
            mixer.music.load(self.music_file)
            mixer.music.play()
    def pause(self):
        if not self.playing_state:
            mixer.music.pause()
            self.playing_state=True
        else:
            mixer.music.unpause()
            self.playing_state = False
    def stop(self):
        mixer.music.stop()
root = Tk()
app= MusicPlayer(root)
root.mainloop()
credit goes to kalebujordan

Summary :

In this article we saw how to make your own MP3 music player in python using Tkinter so about this article you have any query then free to ask me

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.

Понравилась статья? Поделить с друзьями:
  • Как написать свой плагин для майнкрафт
  • Как написать свой социальный статус
  • Как написать свой плагин для minecraft
  • Как написать свой плагин для joomla
  • Как написать свой парсер сайтов