1
我有以下用於播放給定文件夾中音樂的代碼。 的問題是:Porgram無法打開文件無法打開目錄中的音頻文件
import os
import pygame
def playsound(soundfile):
"""Play sound through default mixer channel in blocking manner.
This will load the whole sound into memory before playback
"""
pygame.init()
pygame.mixer.init()
sound = pygame.mixer.Sound(soundfile)
clock = pygame.time.Clock()
sound.play()
print("Playing...")
while pygame.mixer.get_busy():
clock.tick(1000)
def playmusic(soundfile):
"""Stream music with mixer.music module in blocking manner.
This will stream the sound from disk while playing.
"""
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
pygame.mixer.music.load(soundfile)
pygame.mixer.music.play()
print("Playing...")
while pygame.mixer.music.get_busy():
clock.tick(1000)
def stopmusic():
"""stop currently playing music"""
pygame.mixer.music.stop()
def getmixerargs():
pygame.mixer.init()
freq, size, chan = pygame.mixer.get_init()
return freq, size, chan
def initMixer():
BUFFER = 3072 # audio buffer size, number of samples since pygame 1.8.
FREQ, SIZE, CHAN = getmixerargs()
pygame.mixer.init(FREQ, SIZE, CHAN, BUFFER)
try:
initMixer()
for file in os.listdir("./music/"):
if file.endswith(".mp3"):
filename = file
playmusic(filename)
except KeyboardInterrupt: # to stop playing, press "ctrl-c"
stopmusic()
print ("\nPlay Stopped by user")
它給了我以下錯誤:
pygame.error: Couldn't open '1.mp3'
當我刪除了for循環嘗試塊寫文件名= 「music/1.mp3」程序運行時沒有問題。錯誤引用導致playmusic(filename)
和pygame.mixer.music.load(soundfile)
。但我無法弄清楚我在這裏做錯了什麼。 有人嗎?
感謝。它適用於這兩種解決方案。 你能幫助多一點嗎? 如何從目錄中選擇一個隨機文件? 通過傳遞playmusic(隨機(文件名))? –
很高興 - 如果您想播放隨機文件而不是所有文件,請使用我添加到第二次編輯的代碼 – jfbeltran
豎起大拇指。現在工作正常。 –