用到的包
import pygame
import tkinter as tk
from tkinter import messagebox
from tkinter.filedialog import askdirectory
import os,time
窗口和变量
window = tk.Tk()
window.title('播放器')
window.geometry('300x300')
pygame.mixer.init()
value = []
count = [0,0]
flag = []
filepath,musiclist = [],[]
flag.append(False)
value.append(50)
主要函数
def play_music(musiclist,count,times,flag):
if flag[0] == False:
path.set(filepath[0] + '/' + musiclist[count[0]])
filename = musiclist[count[0]].split('.')
pygame.mixer.music.load(musiclist[count[0]])
pygame.mixer.music.set_volume(value[0] / 100)
pygame.mixer.music.play(loops = times,start = 0.0)
flag[0] = True
def selectPath():
path_ = askdirectory()
path.set(path_)
def startMusic():
filepath.clear()
musiclist.clear()
count[1] = 0
filepath.append(path.get())
flag[0] = False
try:
os.chdir(path.get())
for music in os.listdir(path.get()):
filename = music.split('.')
if filename[-1] == 'mp3' or filename[-1] == 'flac':
musiclist.append(music)
count[0] = 0
count[1] += 1
times = 1
play_music(musiclist,count,times,flag)
except Exception as e:
print(e)
tk.messagebox.showerror('错误','请正确选择文件夹')
def quitMusic():
pygame.mixer.music.stop()
window.destroy()
def pauseMusic():
pygame.mixer.music.pause()
def continueMusic():
pygame.mixer.music.unpause()
def nextMusic():
count[0] += 1
if count[0] <= count[1] - 1:
flag[0] = False
times = 1
play_music(musiclist,count,times,flag)
elif count[0] == count[1]:
count[0] = 0
flag[0] = False
times = 1
play_music(musiclist,count,times,flag)
def singleMusic():
pygame.mixer.music.play(loops = -1)
def soundAdd():
value[0] += 5
pygame.mixer.music.set_volume(value[0] / 100)
def soundReduce():
value[0] -= 5
pygame.mixer.music.set_volume(value[0] / 100)
文本框和按钮
path = tk.StringVar()
#path.set('E:/Music')
entry_1 = tk.Entry(window,textvariable = path).place(x = 100,y = 30,width = 180,height = 30)
button_1 = tk.Button(window,text = '选择目录',command = selectPath)
button_1.place(x = 30,y = 30,width = 60,height = 30)
button_2 = tk.Button(window,text = '播放',command = startMusic)
button_2.place(x = 30,y = 80,width = 100,height = 30)
button_3 = tk.Button(window,text = '下一曲',command = nextMusic)
button_3.place(x = 180,y = 80,width = 100,height = 30)
button_4 = tk.Button(window,text = '暂停',command = pauseMusic)
button_4.place(x = 30,y = 140,width = 100,height = 30)
button_5 = tk.Button(window,text = '继续',command = continueMusic)
button_5.place(x = 180,y = 140,width = 100,height = 30)
button_6 = tk.Button(window,text = '升高音量',command = soundAdd)
button_6.place(x = 30,y = 200,width = 100,height = 30)
button_7 = tk.Button(window,text = '降低音量',command = soundReduce)
button_7.place(x = 180,y = 200,width = 100,height = 30)
button_8 = tk.Button(window,text = '单曲循环',command = singleMusic)
button_8.place(x = 30,y = 260,width = 100,height = 30)
button_9 = tk.Button(window,text = '退出',command = quitMusic)
button_9.place(x = 180,y = 260,width = 100,height = 30)
window.mainloop()
以上代码拼接即为完整代码