吴裕雄--天生自然python学习笔记:python 用pygame模块制作一个音效播放器

用 Sound 对象制作一个音效播放器。
应用程序总览
程序在执行后默认会把 WAV 音频文件加载到清单中,单击“播放”按钮可开始
播放,同时显示 “正在播放 xxx 音效”的信息 。
播放过程中,可以通过单击“上一首”“下一首”按钮播放列表中的上一首或下
一首音效;单击“停止播放”按钮可停止播放:单击“结束”按钮则可结束应用程
序井结束音效播放。
def menu(status):
    os.system("cls")
    print("wav 播放器  {}".format(status))
    print("--------------------------------------")
    print("1. 播  放")
    print("2. 上一首")
    print("3. 下一首")
    print("4. 停止播放")
    print("0. 结束程序")
    print("--------------------------------------")
    
def playwav(song):
    global status,sound
    sound = mixer.Sound(wavfiles[index])
    sound.play(loops = 0)    
    status="正在播放 {}".format(wavfiles[index])            
    
def playNewwav(song):
    global status,sound
    sound.stop()
    sound = mixer.Sound(wavfiles[index])
    sound.play(loops = 0)      
    status="正在播放 {}".format(wavfiles[index])   
    
### 主程序从这里开始 ###
    
from pygame import mixer
import glob,os
mixer.init()

source_dir = "F:\pythonBase\pythonex\ch13\wav\"
wavfiles = glob.glob(source_dir+"*.wav")
index=0
status=""
sound = mixer.Sound(wavfiles[index])

while True:
    menu(status)
    choice = int(input("请输入您的选择:"))
    if choice==1:
         playwav(wavfiles[index])
    elif choice==2:
        index +=1
        if index==len(wavfiles):
            index=0 
        playNewwav(wavfiles[index])            
    elif choice==3:
        index -=1
        if index<0:
            index=len(wavfiles)-1  
        playNewwav(wavfiles[index])            
    elif choice==4:
        sound.stop()
        status="停止播放" 
    else:
        break
    
sound.stop()    
print("程序执行完毕!")

音乐播放
music 对象
music 除了可播放 OGG 和 WAV 文件外,还可以播放 MP3 文件。 它比较适合播放
较长的音乐,可以调整音乐播放的位置,并且可以暂停播放, 其功能较 Sound 对象强大。
mixer 的 music 对象提供下列方法 :

例如:播放 mario.mp3 歌曲 一次。 
from pygame import mixer

mixer.init()
mixer.music.load('F:\pythonBase\pythonex\ch13\mp3\mario.mp3')
mixer.music.play()
原文地址:https://www.cnblogs.com/tszr/p/12035553.html