小案例:用Python制作音乐播放器

以下是音乐播放器要实现的功能:

        1.可以通过打开存放音频文件夹来添加音频

        2.可以播放和暂停音频

        3.可以设置播放音量

需要实现音频播放器的模块:

        1.pygame的音频播放功能

        2.easyguifileopenbox函数与oslistdir函数

        3.播放器的窗口和布局我们就是使用PySimpleGUI库来实现。

先给大家展示下程序:

 

首先,我们需要导入所有库:

from pygame import mixer
from PySimpleGUI import Window,Slider,B,T,LB,Frame
from easygui import diropenbox
from os import listdir

然后是pygame音频的初始化:

mixer.init()
mixer.music.set_volume(1) #设置音量(0 - 1)

要想选择播放的音频,我们就需要用列表来存储音频名称和路径

all_music = []      #所有音频的名称
all_music_path = [] #所有音频的路径

然后就是窗口布局:

layout = [
    [Frame('播放列表',
           [
               
                [T('音频播放列表',font = ('楷体',15))],
                [LB(all_music,size = (60,10),key = '-music_list-')],
                [T('正在播放: 空',font = ('楷体',12),key = '-playing-')]
            ],font = ('楷体',16))],
    [T('音量设置',font = ('楷体',14)),Slider(range = (0,100),key = '-volume-',default_value = 100,orientation = 'h',enable_events = 1)],
    [B('添加音频',font = ('楷体',14)),
     B('开始播放',font = ('楷体',14)),
     B('暂停',font = ('楷体',14)),
     B('退出',font = ('楷体',14))
     ]
    ]

接下来就是窗口的事件处理:

window = Window('音乐播放器',layout)
pause = False #做一个音频是否暂停的标记

while 1:
    event,values = window.read()
    if event in (None,'退出'):break

    mixer.music.set_volume(values['-volume-'] / 100)
    if event == '开始播放':
        if pause:
            mixer.music.unpause() #继续播放
            
        else:
            music = values['-music_list-']
            
            if not len(music):
                continue
            else:
                music = music[0]
                if len(music) > 30:
                    window['-playing-'].update('正在播放: {}...'.format(music[:36]))
                else:
                    window['-playing-'].update('正在播放: {}'.format(music))
                mixer.music.load(all_music_path[all_music.index(music)])
                mixer.music.play()
                choose_music = True
            
    elif event == '添加音频':
        music_file = diropenbox()
        
        all_music_path = all_music_path + [music_file + '\' + i for i in listdir(music_file) if i.endswith('.mp3')]
        all_music = all_music + [i.split('\')[-1] for i in all_music_path]
        window['-music_list-'].update(all_music)
        
    elif event == '暂停':
        if mixer.music.get_busy():
            mixer.music.pause() #暂停
            pause = True
        else:
            continue
    
window.close() #循环结束后就关闭窗口

最后是源代码:

from pygame import mixer
from PySimpleGUI import Window,Slider,B,T,LB,Frame
from easygui import diropenbox
from os import listdir

mixer.init()
mixer.music.set_volume(1)

all_music = []
all_music_path = []

layout = [
    [Frame('播放列表',
           [
               
                [T('音频播放列表',font = ('楷体',15))],
                [LB(all_music,size = (60,10),key = '-music_list-')],
                [T('正在播放: 空',font = ('楷体',12),key = '-playing-')]
            ],font = ('楷体',16))],
    [T('音量设置',font = ('楷体',14)),Slider(range = (0,100),key = '-volume-',default_value = 100,orientation = 'h',enable_events = 1)],
    [B('添加音频',font = ('楷体',14)),
     B('开始播放',font = ('楷体',14)),
     B('暂停',font = ('楷体',14)),
     B('退出',font = ('楷体',14))
     ]
    ]

window = Window('音乐播放器',layout)
pause = False

while 1:
    event,values = window.read()
    if event in (None,'退出'):break
    print(values)
    mixer.music.set_volume(values['-volume-'] / 100)
    if event == '开始播放':
        if pause:
            mixer.music.unpause() #继续播放
            print('继续播放')
        else:
            music = values['-music_list-']
            print(music)
            if not len(music):
                continue
            else:
                music = music[0]
                if len(music) > 30:
                    window['-playing-'].update('正在播放: {}...'.format(music[:36]))
                else:
                    window['-playing-'].update('正在播放: {}'.format(music))
                mixer.music.load(all_music_path[all_music.index(music)])
                mixer.music.play()
                choose_music = True
                print('重新播放')
            
    elif event == '添加音频':
        music_file = diropenbox()
        print(music_file)
        all_music_path = all_music_path + [music_file + '\' + i for i in listdir(music_file) if i.endswith('.mp3')]
        all_music = all_music + [i.split('\')[-1] for i in all_music_path]
        window['-music_list-'].update(all_music)
        
    elif event == '暂停':
        if mixer.music.get_busy():
            mixer.music.pause() #暂停
            pause = True
        else:
            continue
    
window.close()    

以上就是全部内容,感谢大家的观看!