Music player in python with source code

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.

"""
krazyprogrammers 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.

Post a Comment

3 Comments

  1. Nice article. An alternative to using pygame's sound component will be the just_playback library. Try it

    ReplyDelete
  2. i have .mp3 files but it is not playing , why is it so ?

    ReplyDelete
  3. how to add lyrics part on these project can u help me out!

    ReplyDelete