Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Music Player
#1
Hi I am trying to build a PlayAll method for my music player. The PlayAll method needs to be able play one song after the other from a playList. The playList is a listofsongs displayed as a listbox in the GUI. The complete code is below minus the unneccesary code.

# Created March 20 2020
# modified April 1 2020

from tkinter import *
from tkinter.filedialog import askdirectory # for selecting our song directory
from tkinter import ttk

#import ttkthemes #works
#help(ttkthemes)

import tkinter as tk
import tkinter.ttk as ttk 
from ttkthemes import ThemedStyle
from PIL import Image

from tkinter import font
import tkinter.messagebox
import os
from os import path
from pygame import mixer
import pygame
from mutagen.mp3 import MP3
import time
import threading
import shutil
from send2trash import send2trash

def playFile():
    pass
    return

def addFile():
    pass
    return 

def delete():
    pass
    return

def clear():
    pass
    return

def copyFiles():
    pass 
    return

def makeDirectory():
    pass
    return

def createPlaylist():
    pass
    return

def deletePlaylist():
    pass
    return    

def openFolder():
    pass
    return

def aboutUs():
    pass
    return

def showDetails():
    pass
    return

def startCount(totalLength):
    pass                    
    return
    
def playMusic():
    pass
    return

def playAll():
    #print('You are here')
    global listbox
    global index
    global statusBar
    global listofsongs
    global len_max

    length = len(listofsongs)

    pygame.init()
    i = 0

    folder = askdirectory()
    os.chdir(folder)

    for file in os.listdir(folder):        
        if (file.endswith(".wav") or file.endswith(".mp3")):
            if len(file) > len_max:
                len_max = len(file)
            
            song = file[3:]
            listboxOne.insert(END,file)
            listofsongs.append(file)

    listboxOne.configure(yscrollcommand = sb1.set,width = len_max)
    length = len(listofsongs)

    while i < length:
        # if not plying play the music
        if pygame.mixer.music.get_busy() == False:
            print(pygame.mixer.music.get_busy())
            #file = listofsongs[i]
            #print('file is ',file)
            pygame.mixer.music.load(listofsongs[i])
            pygame.mixer.music.play()
            statusBar['text'] = 'Playing '  + os.path.basename(listofsongs[i])
            pygame.mixer.music.queue(listofsongs[i])
            
        i = i + 1

    return

def stopMusic():
    pass
    return

def nextSong():
    pass
    return index

def previousSong():
    pass
    return

def setVolume(val):
    pass
    return

def musicVolume():
    pass                      
    return

def musicPlay():
    pass
    return

def getSelectedRow(event):
    pass
    return

def closeWindow():
    if tkinter.messagebox.askokcancel("Close the Music Player", "Do you want to close the Music Player?"):
        stopMusic()
        root.destroy()
        

#root = Tk()
root = tk.Tk()
root.minsize(300,300)
root.title('Music Player')
root.configure(bg='orange')
style = ThemedStyle(root)

##############################
# Themes

##style.set_theme("radiance") #suited for Linux
style.set_theme('plastik') # Looks good
##style.set_theme('clearlooks')
##style.set_theme('elegance')

##############################

mixer.init()  # initialising

root.iconbitmap('Images/player.ico')

global muted
global paused
global listofsongs
global index
global len_max
global path

paused = TRUE
muted = TRUE
listofsongs = []
index = 0
len_max = 40

statusBar = Label(root,text='Welcome to Music Player',relief=SUNKEN,anchor=W, font ='Tahoma 12 italic')
statusBar.pack(side=BOTTOM,fill=X)

leftFrame = Frame(root)
leftFrame.pack(side=LEFT,padx=15,pady=10)

rightFrame = Frame(root)
rightFrame.pack(side=RIGHT,padx=15,ipady=25,ipadx = 25)

topFrame = Frame(rightFrame)
topFrame.pack()

buttonFont = font.Font(family='Tahaoma', size=12, weight='normal')

fileLabel = Label(topFrame,text='Lets play some music')
fileLabel.configure(font =buttonFont)
fileLabel.pack(pady=0)

lengthLabel = Label(topFrame,text='Total length - --:--')
lengthLabel.configure(font =buttonFont)
lengthLabel.pack(pady=0)

currentTimeLabel = Label(topFrame,text='Current Time - --:--',relief = GROOVE)
currentTimeLabel.configure(font =buttonFont)
currentTimeLabel.pack(pady=0)

menubar = Menu(root) # creating menubar
root.config(menu = menubar)
subMenu = Menu(menubar,tearoff = 0)
menubar.add_cascade(label='File',menu = subMenu)
subMenu.add_command(label='Open Folder',command = openFolder)
subMenu.add_command(label='Play File',command = playFile)
#subMenu.add_command(label='Exit',command = root.destroy)

subMenu = Menu(menubar,tearoff = 0)
menubar.add_cascade(label='Help',menu = subMenu)
subMenu.add_command(label='About Us',command = aboutUs)

frameThree = Frame(rightFrame)
frameThree.pack(side=BOTTOM,pady=5,padx=5)

frameTwo = Frame(rightFrame)
frameTwo.pack(side=BOTTOM,pady=5,padx=5)

frameOne = Frame(rightFrame)
frameOne.pack(side=BOTTOM,pady=5,padx=5)

bottomFrameButtons = Frame(leftFrame)
bottomFrameButtons.pack(side=BOTTOM,pady=5,padx=5)

frameButtons = Frame(leftFrame)
frameButtons.pack(side=BOTTOM,pady=5,padx=5)

####################################################################

# Buttons

addButton = Button(frameButtons, text='Add File',command = addFile)
addButton.configure(font=buttonFont)
addButton.pack(side = LEFT)

removeButton = Button(frameButtons, text='Delete File',command = delete)
removeButton.configure(font=buttonFont)
removeButton.pack(side = LEFT)

copyButton = Button(frameButtons, text='Copy Files',command = makeDirectory)
copyButton.configure(font=buttonFont)
copyButton.pack(side = LEFT)

clearButton = Button(frameButtons, text='Clear Files',command = clear)
clearButton.configure(font=buttonFont)
clearButton.pack(side = LEFT)

createPlayListButton = Button(bottomFrameButtons, text='Create Playlist',command = createPlaylist)
createPlayListButton.configure(font=buttonFont,height = 1)
createPlayListButton.pack(side = LEFT)

playListText = StringVar()
playListText = Entry(bottomFrameButtons,textvariable = playListText)
playListText.configure(font=('Tahoma', 15), width = 12)
playListText.pack(side = LEFT)

deletePlayListButton = Button(bottomFrameButtons, text='Delete Playlist',command = deletePlaylist)
deletePlayListButton.configure(font=buttonFont,height = 1)
deletePlayListButton.pack(side = LEFT)

######################################################################

listboxOne = Listbox(leftFrame,font =buttonFont)
sb1 = Scrollbar(leftFrame)
#sb1.grid(row = 0,column = 9, rowspan = 9)
sb1.pack(side=RIGHT)

listboxOne.configure(yscrollcommand = sb1.set,width = len_max)
sb1.configure(command = listboxOne.yview)

listboxOne.bind('<<ListboxSelect>>', getSelectedRow)
listboxOne.pack(side=RIGHT)

# Play Button

photoPlay = PhotoImage(file='Images/playButton.png')
labelPhoto = Label(image=photoPlay)
labelPhoto.photoPlay = photoPlay

playMusicButton = ttk.Button(frameOne,image=photoPlay,command = playMusic)
playMusicButton.pack(side=LEFT,padx=5)
#playMusic.grid(row=1,column=0)

# StopButton

photoStop = PhotoImage(file='Images/stopButton.png')
labelPhoto = Label(image=photoStop)
labelPhoto.photoPlay = photoStop

stopMusicButton = ttk.Button(frameOne,image=photoStop,command = stopMusic)
stopMusicButton.pack(side=LEFT,padx=5)

# Pause Button

photoPause = PhotoImage(file='Images/pauseButton.png')
labelPhoto = Label(image=photoPause)
labelPhoto.photoPause = photoPause

pauseMusicButton = ttk.Button(frameOne,image=photoPause,command = musicPlay)
pauseMusicButton.pack(side=LEFT,padx=5)

# Play All Button

photoPlayAll = PhotoImage(file='Images/playAllButton.png')
labelPhoto = Label(image=photoPlayAll)
labelPhoto.photoPlayAll = photoPlayAll

playAllButton = ttk.Button(frameOne,image=photoPlayAll,command = playAll)
playAllButton.pack(side=LEFT,padx=5)

# Resume Button

photoResume = PhotoImage(file='Images/resumeButton.png')
labelPhoto = Label(image=photoResume)
labelPhoto.photoResume = photoResume

# Previous Button

photoPrevious = PhotoImage(file='Images/previousButton.png')
labelPhoto = Label(image=photoPrevious)
labelPhoto.photoPlay = photoPrevious

previousSongButton = ttk.Button(frameTwo, image=photoPrevious,command = previousSong)
previousSongButton.pack(side=LEFT,padx=5)

# Next Button

photoNext = PhotoImage(file='Images/nextButton.png')
labelPhoto = Label(image=photoNext)
labelPhoto.photoPlay = photoNext

nextSongButton = ttk.Button(frameTwo, image=photoNext,command = nextSong)
nextSongButton.pack(side=LEFT,padx=5)

# volumeButton

photoVolume = PhotoImage(file='Images/volumeButton.png')
labelPhoto = Label(image=photoVolume)
labelPhoto.photoVolume = photoVolume

photoMute = PhotoImage(file='Images/muteButton.png')
labelPhoto = Label(image=photoMute)
labelPhoto.photoMute = photoMute 

volumeButton = ttk.Button(frameTwo,image=photoMute,command = musicVolume)
volumeButton.pack(side=LEFT,padx=5)    

# Volume Control

scale = ttk.Scale(frameThree,from_= 0, to = 100, orient=HORIZONTAL,command = setVolume)
volumePreset = 50
scale.set(volumePreset)
mixer.music.set_volume(volumePreset)
scale.pack(side=LEFT,padx=2,pady=5)
#scale.grid(row=3,column=0,pady = 2)

# Close Button

photoClose = PhotoImage(file='Images/closeButton.png')
labelPhoto = Label(image=photoClose)
labelPhoto.photoClose = photoClose

closeButton = ttk.Button(frameTwo,image=photoClose,command = closeWindow)
closeButton.pack(side=LEFT,padx=2,pady=5)
#closeButton.grid(row=3,column=1,padx = 10)

def onclosing():
    if tkinter.messagebox.askokcancel("Close the Music Player", "Do you want to close the Music Player?"):
        stopMusic()
        root.destroy()

root.protocol("WM_DELETE_WINDOW",onclosing)
root.mainloop() 
Reply
#2
A few things I'd like to point out and ask. First off, not many people want to look through 400 lines of code and interpret everything. It's best for you to cut out the main code that your having a problem with. Also, I don't understand what the problem here is, is there an error, or do you need help on how you should go about coding this? One last thing, from the quick glance over all the code I noticed a few things, a lot of functions, and global variables. First off, global variables are very un-recommended for use, and second, you could probably make use of classes somehow to compact all the functions together into a smaller amount of code.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020