首頁 > 軟體

Python實現多功能音樂播放器詳解

2022-02-16 10:00:24

前言

就是用Python做一個簡易的音樂播放器,廢話不多說,咱們直接開幹

當然,今天做這個肯定不是最簡單的,最簡單的音樂播放器,9行程式碼足以

import time
import pygame

file = r'歌曲路徑'
pygame.mixer.init()
print('正在播放',file)
track = pygame.mixer.music.load(file)
pygame.mixer.music.play()
time.sleep(130)
pygame.mixer.music.stop()

準備工作

知識點和所需模組

1.python基礎知識

2.requests庫

3.time

4.pygame

5.tkinter

6.執行緒

環境

windows

pycharm 2021.2

python 3.8

完整程式碼

# 匯入
import os
import time
import tkinter
import tkinter.filedialog
import threading
import pygame   # pip



root = tkinter.Tk()
root.title('音樂播放器')
root.geometry('460x600+500+100')
root.resizable(False,False)  # 不能拉伸

folder =''
res = []
num = 0
now_music = ''



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=100,width=260,height=300)

    if not folder:
        return

    global playing
    playing = True
    # 根據情況禁用和啟用相應的按鈕
    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():
    """
    點選播放
    :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

        # 建立一個執行緒來播放音樂,當前主執行緒用來接收使用者操作
        t = threading.Thread(target=play)
        t.start()

    elif pause_resume.get() == '暫停':
        # pygame.mixer.init()
        pygame.mixer.music.pause()

        pause_resume.set('繼續')

    elif pause_resume.get() == '繼續':
        # 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
    # 建立執行緒播放音樂,主執行緒用來接收使用者操作
    t = threading.Thread(target=play)
    t.start()


def closeWindow():
    """
    關閉視窗
    :return:
    """
    # 修改變數,結束執行緒中的迴圈

    global playing

    playing = False

    time.sleep(0.3)

    try:

        # 停止播放,如果已停止,

        # 再次停止時會丟擲異常,所以放在例外處理結構中

        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

    # 建立一個執行緒來播放音樂,當前主執行緒用來接收使用者操作

    t = threading.Thread(target=play)

    t.start()


# 視窗關閉
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'


# 標籤
musicName = tkinter.StringVar(root, value='暫時沒有播放音樂...')
labelName = tkinter.Label(root, textvariable=musicName)
labelName.place(x=10, y=30, width=260, height=20)

# 音量控制
# HORIZONTAL表示為水平放置,預設為豎直,豎直為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()

效果展示

簡易版的

還有個半成品的,目前程式碼沒寫完

匯入模組

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)  # 不能拉伸

# 顯示
root.mainloop()

按鈕

# 新增按鈕
buttonChoose = tkinter.Button(root,text='新增')
# 佈局
buttonChoose.place(x=50,y=10,width=50,height=20)

# 播放按鈕
pause_resume = tkinter.StringVar(root,value='播放')
buttonPlay = tkinter.Button(root,textvariable=pause_resume)
buttonPlay.place(x=190,y=10,width=50,height=20)
buttonPlay['state'] = 'disabled'


# 停止按鈕
buttonStop = tkinter.Button(root, text='停止')
buttonStop.place(x=120, y=10, width=50, height=20)
buttonStop['state'] = 'disabled'

# 下一首
buttonNext = tkinter.Button(root, text='下一首')
buttonNext.place(x=260, y=10, width=50, height=20)
buttonNext['state'] = 'disabled'
# 上一首
buttonPrev = tkinter.Button(root, text='上一首')
buttonPrev.place(x=330, y=10, width=50, height=20)
buttonPrev['state'] = 'disabled'


# 標籤
musicName = tkinter.StringVar(root, value='暫時沒有播放音樂...')
labelName = tkinter.Label(root, textvariable=musicName)
labelName.place(x=10, y=30, width=260, height=20)

# 音量控制
# HORIZONTAL表示為水平放置,預設為豎直,豎直為vertical
s = tkinter.Scale(root, label='音量', from_=0, to=1, orient=tkinter.HORIZONTAL,
                  length=240, showvalue=0, tickinterval=2, resolution=0.1)
s.place(x=50, y=50, width=200)

功能

建立一個檔案目錄

folder =''
res = []
num = 0
now_music = ''

音樂讀取功能

def buttonChooseClick():
    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('\','/'))

    if not folder:
        return

    global playing
    playing = True
    # 根據情況禁用和啟用相應的按鈕
    buttonPlay['state'] = 'normal'
    buttonStop['state'] = 'normal'
    # buttonPause['state'] = 'normal'
    pause_resume.set('播放')

顯示已載入的音樂

var2 = tkinter.StringVar()
var2.set(ret)
lb = tkinter.Listbox(root,listvariable=var2)
lb.place(x=50,y=100,width=260,height=300)

播放音樂

def play():
    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():
    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

        # 建立一個執行緒來播放音樂,當前主執行緒用來接收使用者操作
        t = threading.Thread(target=play)
        t.start()

    elif pause_resume.get() == '暫停':
        # pygame.mixer.init()
        pygame.mixer.music.pause()

        pause_resume.set('繼續')

    elif pause_resume.get() == '繼續':
        # pygame.mixer.init()
        pygame.mixer.music.unpause()

        pause_resume.set('暫停')

停止播放

def buttonStopClick():
    global playing
    playing = False
    pygame.mixer.music.stop()

下一首

def buttonNextClick():
    global playing
    playing = False
    pygame.mixer.music.stop()
    global num
    if len(res) == num:
        num = 0

    playing = True
    # 建立執行緒播放音樂,主執行緒用來接收使用者操作
    t = threading.Thread(target=play)
    t.start()

上一首

def buttonPrevClick():
    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
    # 建立一個執行緒來播放音樂,當前主執行緒用來接收使用者操作
    t = threading.Thread(target=play)
    t.start()

音量控制

def control_voice(value=0.5):
    pygame.mixer.music.set_volume(float(value))

關閉視窗

def closeWindow():
    # 修改變數,結束執行緒中的迴圈
    global playing
    playing = False
    time.sleep(0.3)

    try:
        # 停止播放,如果已停止,
        # 再次停止時會丟擲異常,所以放在例外處理結構中
        pygame.mixer.music.stop()
        pygame.mixer.quit()

    except:
        pass
    root.destroy()

到此這篇關於Python實現多功能音樂播放器詳解的文章就介紹到這了,更多相關Python音樂播放器內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com