pygame.mixer 提供音訊播放功能,支援 WAV、OGG、MP3 (需系統編解碼器)、MIDI (需 timidity 或 FluidSynth 後端)。
import pygame as pg
import sys
def play_music(music_file, volume=0.8):
"""阻塞式播放音訊檔案"""
# 初始化混音器 (頻率、位元深度、聲道、緩衝區)
pg.mixer.init(frequency=44100, size=-16, channels=2, buffer=2048)
pg.mixer.music.set_volume(volume)
clock = pg.time.Clock()
try:
pg.mixer.music.load(music_file)
print(f"載入: {music_file}")
except pg.error as e:
print(f"載入失敗: {music_file} - {e}")
return
pg.mixer.music.play()
print("播放中... (Ctrl+C 停止)")
try:
while pg.mixer.music.get_busy():
clock.tick(30) # 限制輪詢頻率
except KeyboardInterrupt:
print("\n使用者中斷,淡出停止...")
pg.mixer.music.fadeout(1000)
pg.mixer.music.stop()
finally:
pg.mixer.quit()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("用法: python play_audio.py <音訊檔案>")
sys.exit(1)
play_music(sys.argv[1])
| 參數 | 預設值 | 說明 |
|---|---|---|
frequency | 44100 | 取樣率 (Hz),CD 品質 44100 |
size | -16 | 位元深度:正數=無號,負數=有號,16-bit 標準 |
channels | 2 | 1=單聲道,2=立體聲 |
buffer | 4096 | 緩衝區大小 (樣本數),越小延遲越低但易斷音 |
pg.mixer.init()
# 音效短小、需疊加播放用 Sound
shoot_sound = pg.mixer.Sound('shoot.wav')
explosion_sound = pg.mixer.Sound('explosion.ogg')
# 播放 (非阻塞)
shoot_sound.play()
explosion_sound.play()
# 音量控制
shoot_sound.set_volume(0.5)
# 等待播放結束 (可選)
while pg.mixer.get_busy():
pg.time.wait(100)
timidity 或 fluidsynth:sudo apt-get install timidity。while get_busy() 阻塞,改用事件驅動或非阻塞檢查。pg.mixer.quit()。