王剑编程网

分享专业编程知识与实战技巧

【原创】音乐播放器系列-1:Python Pygame(附完整源码)

△ 内容:

1 音乐播放器图片和操作图展示。

2 代码讲解,提供代码可读性和锻炼python编程能力,是学习python的一个生动的好项目。

3 附完整源码,个人原创,无偿奉献出来。

4 适合人群:编程爱好者,python学习者,学生。

△ 图-1:

△ 图-2:

△ 音乐播放器特点:

1 播放按钮:上一首、播放、暂停、恢复、停止、下一首,鼠标点击操作。

2 播放列表:默认文件夹下的音乐mp3读取并显示。

3 音量:鼠标可调节。

4 音乐播放进度条:当前时间,播放进度条,歌曲总时间。

5 歌词显示,当前播放歌曲名显示。

△ 文件夹布局图:

图-3 注意:pygame的中文字体simsun.ttc 需要自己提前下载,或者自己采用其他中文字体。

图-4 歌曲mp3和歌词lrc需要自己提前下载,可放自己喜欢的其他歌曲和配套的歌词lrc。

△ 操作示范:

△ 代码详解:

第1步:导入模块

import pygame,os,sys
from mutagen.mp3 import MP3

第2步:初始化:

特色一:本地文件夹初始化。

pygame.init() # pygame初始化
PATH_ROOT = os.path.split(sys.argv[0])[0]  # 本地文件夹初始化
window_width, window_height = 1000, 1000 # 窗口大小设置
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Music Player") # 窗口标题名
font = pygame.font.Font("/".join([PATH_ROOT, "simsun.ttc"]) , 30) # 中文字体设置
volume = 0.5  # 初始音量值

第3步:默认音乐播放文件夹

特色二:本地文件夹song里有mp3和lrc文件,匹配和对应的,读取出来有一定难度。

# 第3步:默认音乐播放文件夹
# 3-1 定义函数:找文件夹和文件夹匹配
def find_files_with_suffix(folder_path, suffix):
    all_files = os.listdir(folder_path)
    filtered_files = [file for file in all_files if file.endswith(suffix)]
    return filtered_files

# 3-2默认音乐播放文件夹
music_dir = "/".join([PATH_ROOT, "song"])
music_files = find_files_with_suffix(music_dir, ".mp3")

第4步:播放音乐的初始化

特色三:这里有歌曲和歌词初始化,歌词出来问题。

# 第4步:播放音乐的初始化
# 4-1 播放音乐mp3
current_track = 0 # 初始播放列表文件位置
pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track])) # 加载音乐

# 4-2 歌词初始化
def LRCopen():
    global musicL,musicDict,current_track
    name = music_files[current_track].split('.')[0]
    lrc_dir = "/".join([PATH_ROOT, "song",name+'.lrc'])
    # 歌词
    file1 = open(lrc_dir, "r", encoding="utf-8")
    musicList=file1.readlines()
    musicDict={}  #用字典来保存该时刻对应的歌词
    musicL=[]

    for i in musicList:
        musicTime=i.split("]")
        for j in musicTime[:-1]:
            musicTime1=j[1:].split(":")
            musicTL=float(musicTime1[0])*60+float(musicTime1[1])
            musicTL=float("%.2f" %musicTL)

            musicDict[musicTL]=musicTime[-1]
    for i in musicDict:
        musicL.append(float("%.2f" %i))
    musicL.sort()
    return musicL,musicDict

# 4-3 歌词初始化,时间和歌词
musicL=LRCopen()[0]
musicDict=LRCopen()[1]

第5步:函数功能定义

播放按钮的功能函数定义和时间格式化函数。

# 第5步:函数功能定义
# 5-1 播放
def play_track():
    pygame.mixer.music.play()

# 5-2 暂停
def pause_track():
    pygame.mixer.music.pause()

# 5-3 恢复
def resume_track():
    pygame.mixer.music.unpause()

# 5-4 停止
def stop_track():
    pygame.mixer.music.stop()

# 5-5 下一首
def next_track():
    global current_track,musicL,musicDict
    current_track = (current_track + 1) % len(music_files)
    pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track]))

    musicL=LRCopen()[0]
    musicDict=LRCopen()[1]
    play_track()

# 5-6 上一首
def previous_track():
    global current_track,musicL,musicDict
    current_track = (current_track - 1) % len(music_files)
    pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track]))

    musicL=LRCopen()[0]
    musicDict=LRCopen()[1]
    play_track()

# 5-7 音乐时间获取
def duration_format(d):
    d = int(float(d))
    dd = int(d % (60*60))
    min = int(dd / 60)
    sec = int(dd % 60)
    return "{:0>2}:{:0>2}".format(min, sec)

第6步:循环

这里面是重点,分点讲解。

6-1 循环启动和退出设置

# 第6步:循环启动
running = True
while running:
    # 6-1 退出设置
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

6-2 部分窗口布局

这里窗口布局主要是播放列表,音量调节,正在播放歌曲名和播放按钮的设置和布局,所以是部分布局,不包括播放进度条和歌词显示。

    # 6-2 窗口布局
    # 6-2-1 播放列表框
    rectCoord = [10, 30, 780, 300]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)
    pygame.draw.rect(window,(0,0,0),(30,50,700,250)) # 黑色框
    # 播放列表
    playlist_text=font.render("Playlist:", True,'white')
    window.blit(playlist_text, (50, 50))
    for i in range(len(music_files)):
        playlist_text=font.render(music_files[i], True, 'white')
        window.blit(playlist_text, (50, 50+30*(i+1)))

    # 6-2-2 音量
    rectCoord = [820, 30, 150, 300]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)
    volume_text = font.render("音 量", True, 'red',bgcolor='white') # 音量标签
    window.blit(volume_text, (850, 50))
    # 音量条bar
    pygame.draw.rect(window, 'white', (880, 100, 20, 200))
    pygame.draw.rect(window, 'green', (880, int(300 - volume * 100), 20, int(volume * 100)))

    # 6-2-3 正在播放歌曲
    rectCoord = [10, 350, 980, 100]  # 框
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)  
    nowplayingsong=font.render("Now Playing : "+music_files[current_track], True,'white')
    pygame.draw.rect(window,(0,0,0),(30,360,900,80)) # 黑色框
    window.blit(nowplayingsong, (50, 370)) # 正在播放歌曲名

    # 6-2-4 按钮
    # 6-2-4-1 按钮框
    rectCoord = [10, 470, 980, 100]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)

    # 6-2-4-2 按钮定义
    play_text = font.render("播 放", True, 'red',bgcolor='white')
    pause_text = font.render("暂 停", True,'red',bgcolor='white')
    resume_text = font.render("恢 复", True, 'red',bgcolor='white')
    stop_text = font.render("停 止", True, 'red',bgcolor='white')
    next_text = font.render("下一首", True, 'red',bgcolor='white')
    previous_text = font.render("上一首", True, 'red',bgcolor='white')

    # 6-2-4-3 按钮位置
    window.blit(previous_text, (50, 500))
    window.blit(play_text, (200, 500))
    window.blit(pause_text, (350, 500))
    window.blit(resume_text, (500, 500))
    window.blit(stop_text, (650, 500))
    window.blit(next_text, (800, 500))

6-3 鼠标事件

在pygame中用鼠标点击操作,比如点击按钮和调节音量。

    # 6-3 鼠标事件
    mouse_x, mouse_y = pygame.mouse.get_pos()
    # 播 放
    if 200 <= mouse_x <= 200 + play_text.get_width() and 500 <= mouse_y <= 500 + play_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            play_track()
    # 暂停
    elif 350 <= mouse_x <= 350 + pause_text.get_width() and 500 <= mouse_y <= 500 + pause_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            pause_track()
    # 恢复
    elif 500 <= mouse_x <= 500 + resume_text.get_width() and 500 <= mouse_y <= 500 + resume_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            resume_track()
    # 停止
    elif 650 <= mouse_x <= 650 + stop_text.get_width() and 500 <= mouse_y <= 500 + stop_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            stop_track()
    # 下一首
    elif 800 <= mouse_x <= 800 + next_text.get_width() and 500 <= mouse_y <= 500 + next_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            next_track()
    # 上一首
    elif 50 <= mouse_x <= 50 + previous_text.get_width() and 500 <= mouse_y <= 500 + previous_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            previous_track()
    # 音乐调节
    elif 850 <= mouse_x <= 950 and 100 <= mouse_y <= 300:
        if pygame.mouse.get_pressed()[0]:
            volume = (300 - mouse_y) / 100
            pygame.mixer.music.set_volume(volume)

6-4 音乐播放进度条

    # 6-4 音乐播放进度条
    # 计时器:用于播放进度条
    RATE = pygame.USEREVENT + 1 # 用户自定义的进度条事件
    # 建立一个定时器,50毫秒触发一次用户自定义事件
    pygame.time.set_timer(RATE, 50)
    clock = pygame.time.Clock()

    # 画进度条播放框
    rectCoord = [10, 880, 980, 100]
    # 生成长方体对象
    rect = pygame.Rect(rectCoord)
    # 在屏幕上用定义的颜色、形状、位置、线宽画长方体
    pygame.draw.rect(window, 'white', rect, 2)

    # 进度条框
    PROGRESSPOS = pygame.Rect(250,920,500,10)  # 进度条,全局变量
    rec0 = PROGRESSPOS.copy()  # 进度条背景条框
    pygame.draw.rect(window, "white", rec0)  # 进度条背景条框
    
    # 初始化音乐播放当前时间:左侧时间
    pygame.draw.rect(window,(0,0,0),(140,900,100,50)) # 黑色框
    txt=duration_format(0)
    img = font.render(txt, 1, 'white')  # 当前歌曲播放时间
    window.blit(img, (142,910)) # 位置

    # 获取音乐总时长,右侧时间
    mp3_info = MP3(os.path.join(music_dir, music_files[current_track]))
    length = mp3_info.info.length   # 歌曲时长(秒)
    pygame.draw.rect(window,(0,0,0),(800,900,100,50)) # 黑色框
    duration = round(length)
    d_f=duration_format(duration)
    songlenght = font.render(d_f, 1, 'white') # 歌曲总时长
    window.blit(songlenght, (810,910))
    
    # 音乐播放时间和进度条
    if pygame.mixer.music.get_busy():
        sec = pygame.mixer.music.get_pos() / 1000
        pygame.draw.rect(window,(0,0,0),(140,900,100,50)) # 黑色框

        h = int(sec / 60 / 60)
        m = int((sec - h*60*60) / 60)
        s = int(sec - h*60*60 - m*60)
        txt = '{1:02d}:{2:02d}'.format(h, m, s)
        img = font.render(txt, 1, 'white')  # 当前歌曲播放时间
        window.blit(img, (142,910)) # 位置

        pygame.draw.rect(window,(0,0,0),(800,900,100,50)) # 黑色框
        window.blit(songlenght, (810,910))
        # 获取当前播放的时间
        sec %= length  # 如果循环播放,需要处理
        rate = sec / length
        # 画进度条
        rec = PROGRESSPOS.copy()
        rec.width = PROGRESSPOS.width * rate  # 长方形宽度
        # 画进度条绿色进度
        pygame.draw.rect(window, "green", rec)

6-5 歌词显示

    # 6-5 歌词显示
    current = pygame.mixer.music.get_pos() / 1000 # 毫秒
    currenttime=float("%.2f" %current)
    for i in range(len(musicL)):
        if musicL[i]==currenttime:
            txtsurf = font.render('', True, 'white')
            window.blit(txtsurf,(300, 700))
            pygame.draw.rect(window,(255,0,0),(50,620,900,200)) # 红色框
            # 歌词动态显示
            txtsurf = font.render(musicDict.get(musicL[i]), True, 'white')
            window.blit(txtsurf,(300, 700))
            pygame.display.update()

    pygame.display.flip()

第7步:退出

# 第7步:退出
pygame.quit()

△ 备注:

1 代码还可以优化,还可以更简洁。

2有一个小小bug,那就是因为初始化播放歌曲和歌词,所以在点击上一首或者下一首时,会可能有第一首歌曲重复出现,一闪而过,不注意是看不出来的。同时也悄悄证明是我的原创代码。

△ 附完整源码:


# 第1步:导入模块
import pygame,os,sys
from mutagen.mp3 import MP3

# 第2步:初始化
pygame.init() # pygame初始化
PATH_ROOT = os.path.split(sys.argv[0])[0]  # 本地文件夹初始化
window_width, window_height = 1000, 1000 # 窗口大小设置
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Music Player") # 窗口标题名
font = pygame.font.Font("/".join([PATH_ROOT, "simsun.ttc"]) , 30) # 中文字体设置
volume = 0.5  # 初始音量值

# 第3步:默认音乐播放文件夹
# 3-1 定义函数:找文件夹和文件夹匹配
def find_files_with_suffix(folder_path, suffix):
    all_files = os.listdir(folder_path)
    filtered_files = [file for file in all_files if file.endswith(suffix)]
    return filtered_files

# 3-2默认音乐播放文件夹
music_dir = "/".join([PATH_ROOT, "song"])
music_files = find_files_with_suffix(music_dir, ".mp3")

# 第4步:播放音乐的初始化
# 4-1 播放音乐mp3
current_track = 0 # 初始播放列表文件位置
pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track])) # 加载音乐

# 4-2 歌词初始化
def LRCopen():
    global musicL,musicDict,current_track
    name = music_files[current_track].split('.')[0]
    lrc_dir = "/".join([PATH_ROOT, "song",name+'.lrc'])
    # 歌词
    file1 = open(lrc_dir, "r", encoding="utf-8")
    musicList=file1.readlines()
    musicDict={}  #用字典来保存该时刻对应的歌词
    musicL=[]

    for i in musicList:
        musicTime=i.split("]")
        for j in musicTime[:-1]:
            musicTime1=j[1:].split(":")
            musicTL=float(musicTime1[0])*60+float(musicTime1[1])
            musicTL=float("%.2f" %musicTL)

            musicDict[musicTL]=musicTime[-1]
    for i in musicDict:
        musicL.append(float("%.2f" %i))
    musicL.sort()
    return musicL,musicDict

# 4-3 歌词初始化,时间和歌词
musicL=LRCopen()[0]
musicDict=LRCopen()[1]

# 第5步:函数功能定义
# 5-1 播放
def play_track():
    pygame.mixer.music.play()

# 5-2 暂停
def pause_track():
    pygame.mixer.music.pause()

# 5-3 恢复
def resume_track():
    pygame.mixer.music.unpause()

# 5-4 停止
def stop_track():
    pygame.mixer.music.stop()

# 5-5 下一首
def next_track():
    global current_track,musicL,musicDict
    current_track = (current_track + 1) % len(music_files)
    pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track]))

    musicL=LRCopen()[0]
    musicDict=LRCopen()[1]
    play_track()

# 5-6 上一首
def previous_track():
    global current_track,musicL,musicDict
    current_track = (current_track - 1) % len(music_files)
    pygame.mixer.music.load(os.path.join(music_dir, music_files[current_track]))

    musicL=LRCopen()[0]
    musicDict=LRCopen()[1]
    play_track()

# 5-7 音乐时间获取
def duration_format(d):
    d = int(float(d))
    dd = int(d % (60*60))
    min = int(dd / 60)
    sec = int(dd % 60)
    return "{:0>2}:{:0>2}".format(min, sec)


# 第6步:循环启动
running = True
while running:
    # 6-1 退出设置
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 6-2 窗口布局
    # 6-2-1 播放列表框
    rectCoord = [10, 30, 780, 300]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)
    pygame.draw.rect(window,(0,0,0),(30,50,700,250)) # 黑色框
    # 播放列表
    playlist_text=font.render("Playlist:", True,'white')
    window.blit(playlist_text, (50, 50))
    for i in range(len(music_files)):
        playlist_text=font.render(music_files[i], True, 'white')
        window.blit(playlist_text, (50, 50+30*(i+1)))

    # 6-2-2 音量
    rectCoord = [820, 30, 150, 300]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)
    volume_text = font.render("音 量", True, 'red',bgcolor='white') # 音量标签
    window.blit(volume_text, (850, 50))
    # 音量条bar
    pygame.draw.rect(window, 'white', (880, 100, 20, 200))
    pygame.draw.rect(window, 'green', (880, int(300 - volume * 100), 20, int(volume * 100)))

    # 6-2-3 正在播放歌曲
    rectCoord = [10, 350, 980, 100]  # 框
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)  
    nowplayingsong=font.render("Now Playing : "+music_files[current_track], True,'white')
    pygame.draw.rect(window,(0,0,0),(30,360,900,80)) # 黑色框
    window.blit(nowplayingsong, (50, 370)) # 正在播放歌曲名

    # 6-2-4 按钮
    # 6-2-4-1 按钮框
    rectCoord = [10, 470, 980, 100]
    rect = pygame.Rect(rectCoord)
    pygame.draw.rect(window, 'white', rect, 2)

    # 6-2-4-2 按钮定义
    play_text = font.render("播 放", True, 'red',bgcolor='white')
    pause_text = font.render("暂 停", True,'red',bgcolor='white')
    resume_text = font.render("恢 复", True, 'red',bgcolor='white')
    stop_text = font.render("停 止", True, 'red',bgcolor='white')
    next_text = font.render("下一首", True, 'red',bgcolor='white')
    previous_text = font.render("上一首", True, 'red',bgcolor='white')

    # 6-2-4-3 按钮位置
    window.blit(previous_text, (50, 500))
    window.blit(play_text, (200, 500))
    window.blit(pause_text, (350, 500))
    window.blit(resume_text, (500, 500))
    window.blit(stop_text, (650, 500))
    window.blit(next_text, (800, 500))
    
    # 6-3 鼠标事件
    mouse_x, mouse_y = pygame.mouse.get_pos()
    # 播 放
    if 200 <= mouse_x <= 200 + play_text.get_width() and 500 <= mouse_y <= 500 + play_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            play_track()
    # 暂停
    elif 350 <= mouse_x <= 350 + pause_text.get_width() and 500 <= mouse_y <= 500 + pause_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            pause_track()
    # 恢复
    elif 500 <= mouse_x <= 500 + resume_text.get_width() and 500 <= mouse_y <= 500 + resume_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            resume_track()
    # 停止
    elif 650 <= mouse_x <= 650 + stop_text.get_width() and 500 <= mouse_y <= 500 + stop_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            stop_track()
    # 下一首
    elif 800 <= mouse_x <= 800 + next_text.get_width() and 500 <= mouse_y <= 500 + next_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            next_track()
    # 上一首
    elif 50 <= mouse_x <= 50 + previous_text.get_width() and 500 <= mouse_y <= 500 + previous_text.get_height():
        if pygame.mouse.get_pressed()[0]:
            previous_track()
    # 音乐调节
    elif 850 <= mouse_x <= 950 and 100 <= mouse_y <= 300:
        if pygame.mouse.get_pressed()[0]:
            volume = (300 - mouse_y) / 100
            pygame.mixer.music.set_volume(volume)
    

    # 6-4 音乐播放进度条
    # 计时器:用于播放进度条
    RATE = pygame.USEREVENT + 1 # 用户自定义的进度条事件
    # 建立一个定时器,50毫秒触发一次用户自定义事件
    pygame.time.set_timer(RATE, 50)
    clock = pygame.time.Clock()

    # 画进度条播放框
    rectCoord = [10, 880, 980, 100]
    # 生成长方体对象
    rect = pygame.Rect(rectCoord)
    # 在屏幕上用定义的颜色、形状、位置、线宽画长方体
    pygame.draw.rect(window, 'white', rect, 2)

    # 进度条框
    PROGRESSPOS = pygame.Rect(250,920,500,10)  # 进度条,全局变量
    rec0 = PROGRESSPOS.copy()  # 进度条背景条框
    pygame.draw.rect(window, "white", rec0)  # 进度条背景条框
    
    # 初始化音乐播放当前时间:左侧时间
    pygame.draw.rect(window,(0,0,0),(140,900,100,50)) # 黑色框
    txt=duration_format(0)
    img = font.render(txt, 1, 'white')  # 当前歌曲播放时间
    window.blit(img, (142,910)) # 位置

    # 获取音乐总时长,右侧时间
    mp3_info = MP3(os.path.join(music_dir, music_files[current_track]))
    length = mp3_info.info.length   # 歌曲时长(秒)
    pygame.draw.rect(window,(0,0,0),(800,900,100,50)) # 黑色框
    duration = round(length)
    d_f=duration_format(duration)
    songlenght = font.render(d_f, 1, 'white') # 歌曲总时长
    window.blit(songlenght, (810,910))
    
    # 音乐播放时间和进度条
    if pygame.mixer.music.get_busy():
        sec = pygame.mixer.music.get_pos() / 1000
        pygame.draw.rect(window,(0,0,0),(140,900,100,50)) # 黑色框

        h = int(sec / 60 / 60)
        m = int((sec - h*60*60) / 60)
        s = int(sec - h*60*60 - m*60)
        txt = '{1:02d}:{2:02d}'.format(h, m, s)
        img = font.render(txt, 1, 'white')  # 当前歌曲播放时间
        window.blit(img, (142,910)) # 位置

        pygame.draw.rect(window,(0,0,0),(800,900,100,50)) # 黑色框
        window.blit(songlenght, (810,910))
        # 获取当前播放的时间
        sec %= length  # 如果循环播放,需要处理
        rate = sec / length
        # 画进度条
        rec = PROGRESSPOS.copy()
        rec.width = PROGRESSPOS.width * rate  # 长方形宽度
        # 画进度条绿色进度
        pygame.draw.rect(window, "green", rec)
    
    # 6-5 歌词显示
    current = pygame.mixer.music.get_pos() / 1000 # 毫秒
    currenttime=float("%.2f" %current)
    for i in range(len(musicL)):
        if musicL[i]==currenttime:
            txtsurf = font.render('', True, 'white')
            window.blit(txtsurf,(300, 700))
            pygame.draw.rect(window,(255,0,0),(50,620,900,200)) # 红色框
            # 歌词动态显示
            txtsurf = font.render(musicDict.get(musicL[i]), True, 'white')
            window.blit(txtsurf,(300, 700))
            pygame.display.update()

    pygame.display.flip()

# 第7步:退出
pygame.quit()
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言