基于Python制作簡單的音樂播放器
介紹
這是一個(gè)簡單的音樂播放器程序,使用了Python的tkinter庫和pygame庫。程序的主要功能包括:
- 添加音樂文件夾
- 播放音樂
- 暫停/繼續(xù)播放
- 停止播放
- 下一首
- 上一首
- 音量控制
實(shí)現(xiàn)思路
程序首先導(dǎo)入了所需的庫,然后創(chuàng)建了一個(gè)tkinter窗口,設(shè)置了窗口標(biāo)題、大小和不可拉伸。
接下來,定義了幾個(gè)全局變量,如文件夾路徑、音樂列表、當(dāng)前播放的音樂索引等。然后定義了幾個(gè)函數(shù),如buttonChooseClick、play、buttonPlayClick、buttonStopClick、buttonNextClick、buttonPrevClick、control_voice等。
buttonChooseClick函數(shù)用于選擇要播放的音樂文件夾,并顯示音樂列表。play函數(shù)用于播放音樂,使用pygame庫實(shí)現(xiàn)。buttonPlayClick函數(shù)用于開始播放音樂,buttonStopClick函數(shù)用于停止播放音樂,buttonNextClick函數(shù)用于播放下一首音樂,buttonPrevClick函數(shù)用于播放上一首音樂。control_voice函數(shù)用于控制音量。
最后,定義了幾個(gè)按鈕的點(diǎn)擊事件,并設(shè)置了按鈕的狀態(tài)(如禁用和啟用),以及窗口的關(guān)閉事件。
在root.mainloop()中,程序開始運(yùn)行,顯示窗口,等待用戶操作。
實(shí)現(xiàn)代碼
首先要下載一些音樂到本地
然后就可以附源碼了:
# 導(dǎo)入
import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame
root = tkinter.Tk()
root.title('音樂播放器')
root.geometry('460x600+500+100')
root.resizable(False,False) # 不能拉伸
folder =''
res = []
num = 0
now_music = ''
num1 = 100
def buttonChooseClick():
"""
添加文件夾
:return:
"""
global folder
global res
if not folder:
folder = tkinter.filedialog.askdirectory()
musics = [folder + '\\' + music
for music in os.listdir(folder) \
\
if music.endswith(('.mp3','.wav','.ogg'))]
ret = []
for i in musics:
ret.append(i.split('\\')[1:])
res.append(i.replace('\\','/'))
var2 = tkinter.StringVar()
var2.set(ret)
lb = tkinter.Listbox(root,listvariable=var2)
lb.place(x=50,y=110,width=360,height=400)
if not folder:
return
global playing
playing = True
# 根據(jù)情況禁用和啟用相應(yīng)的按鈕
buttonPlay['state'] = 'normal'
buttonStop['state'] = 'normal'
# =buttonPause['state'] = 'normal'
pause_resume.set('播放')
def play():
"""
播放音樂
:return:
"""
if len(res):
pygame.mixer.init()
global num
while playing:
if not pygame.mixer.music.get_busy():
netxMusic = res[num]
print(netxMusic)
print(num)
pygame.mixer.music.load(netxMusic.encode())
# 播放
pygame.mixer.music.play(1)
if len(res) -1 == num:
num = 0
else:
num = num + 1
netxMusic = netxMusic.split('\\')[1:]
musicName.set('playing......' + ''.join(netxMusic))
else:
time.sleep(0.1)
def buttonPlayClick():
"""
點(diǎn)擊播放
:return:
"""
buttonNext['state'] = 'normal'
buttonPrev['state'] = 'normal'
# 選擇要播放的音樂文件夾
if pause_resume.get() == '播放':
pause_resume.set('暫停')
global folder
if not folder:
folder = tkinter.filedialog.askdirectory()
if not folder:
return
global playing
playing = True
# 創(chuàng)建一個(gè)線程來播放音樂,當(dāng)前主線程用來接收用戶操作
t = threading.Thread(target=play)
t.start()
elif pause_resume.get() == '暫停':
# pygame.mixer.init()
pygame.mixer.music.pause()
pause_resume.set('繼續(xù)')
elif pause_resume.get() == '繼續(xù)':
# pygame.mixer.init()
pygame.mixer.music.unpause()
pause_resume.set('暫停')
def buttonStopClick():
"""
停止播放
:return:
"""
global playing
playing = False
pygame.mixer.music.stop()
def buttonNextClick():
"""
下一首
:return:
"""
global playing
playing = False
pygame.mixer.music.stop()
global num
if len(res) == num:
num = 0
playing = True
# 創(chuàng)建線程播放音樂,主線程用來接收用戶操作
t = threading.Thread(target=play)
t.start()
def closeWindow():
"""
關(guān)閉窗口
:return:
"""
# 修改變量,結(jié)束線程中的循環(huán)
global playing
playing = False
time.sleep(0.3)
try:
# 停止播放,如果已停止,
# 再次停止時(shí)會(huì)拋出異常,所以放在異常處理結(jié)構(gòu)中
pygame.mixer.music.stop()
pygame.mixer.quit()
except:
pass
root.destroy()
def control_voice(value=0.5):
"""
聲音控制
:param value: 0.0-1.0
:return:
"""
pygame.mixer.music.set_volume(float(value))
def buttonPrevClick():
"""
上一首
:return:
"""
global playing
playing = False
pygame.mixer.music.stop()
#
pygame.mixer.quit()
global num
num += 1
num -= 1
if num == 0:
num = len(res) - 2
# num -= 1
elif num == len(res) - 1:
num -= 2
else:
num -= 2
# num -= 1
print(num)
playing = True
# 創(chuàng)建一個(gè)線程來播放音樂,當(dāng)前主線程用來接收用戶操作
t = threading.Thread(target=play)
t.start()
# 窗口關(guān)閉
root.protocol('WM_DELETE_WINDOW', closeWindow)
# 添加按鈕
buttonChoose = tkinter.Button(root,text='添加',command=buttonChooseClick)
# 布局
buttonChoose.place(x=50,y=10,width=50,height=20)
# 播放按鈕
pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume,command=buttonPlayClick)
buttonPlay.place(x=190,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'
# 停止按鈕
buttonStop = tkinter.Button(root, text='停止',command=buttonStopClick)
buttonStop.place(x=120, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'
# 下一首
buttonNext = tkinter.Button(root, text='下一首',command=buttonNextClick)
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'
# 上一首
buttonPrev = tkinter.Button(root, text='上一首',command=buttonPrevClick)
buttonPrev.place(x=330, y=10, width=50, height=20)
buttonPrev['state'] = 'disabled'
# 標(biāo)簽
musicName = tkinter.StringVar(root, value='暫時(shí)沒有播放音樂...')
labelName = tkinter.Label(root, textvariable=musicName)
labelName.place(x=10, y=30, width=260, height=20)
# 音量控制
# HORIZONTAL表示為水平放置,默認(rèn)為豎直,豎直為vertical
s = tkinter.Scale(root, label='音量', from_=0, to=1, orient=tkinter.HORIZONTAL,
length=240, showvalue=0, tickinterval=2, resolution=0.1,command=control_voice)
s.place(x=50, y=50, width=200)
# 顯示
root.mainloop()
效果圖

到此這篇關(guān)于基于Python制作簡單的音樂播放器的文章就介紹到這了,更多相關(guān)Python音樂播放器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基于Gensim實(shí)現(xiàn)文本相似度/匹配/查重
Gensim是基于Python語言的自然語言處理庫,用來主題建模、文本相似度等文本處理任務(wù),下面我們就來看看如何使用Gensim實(shí)現(xiàn)文本相似度/匹配/查重等操作吧2024-03-03
在Ubuntu系統(tǒng)下安裝使用Python的GUI工具wxPython
這篇文章主要介紹了在Ubuntu系統(tǒng)下安裝使用Python的GUI工具wxPython的方法,wxPython可以為Python提供強(qiáng)大的圖形化界面開發(fā)支持,需要的朋友可以參考下2016-02-02
Python實(shí)現(xiàn)服務(wù)端渲染SSR的示例代碼
服務(wù)端渲染是一種常見的技術(shù)策略,特別是在需要改善網(wǎng)站的搜索引擎優(yōu)化(SEO)和首屏加載時(shí)間的場(chǎng)景下,本文將介紹如何利用?Python?實(shí)現(xiàn)?SSR,感興趣的可以了解下2024-02-02
Python中循環(huán)引用(import)失敗的解決方法
在python中常常會(huì)遇到循環(huán)import即circular import的問題,下面這篇文章主要給大家介紹了關(guān)于Python中循環(huán)引用(import)失敗的解決方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04

