2017-09-22 14 views
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)。但我無法弄清楚我在這裏做錯了什麼。 有人嗎?

回答

2

os.listdir()不會爲您提供文件的完整路徑,因此它不會包含路徑的./music/部分。你可以簡單地將線更改爲:

filename = "./music/" + file 
playmusic(filename) 

甚至更​​好,使用os.path避免古怪行爲

編輯:這實際上是一個很大的用例水珠!您可以使用通配符來抓取音樂文件夾中的所有mp3文件。 Glob還會返回文件的完整路徑(./music/song1.mp3),而不是原始文件名(song1.mp3)。

from glob import glob 

filenames = glob('./music/*.mp3') 
for filename in filenames: 
    playmusic(filename) 

編輯2:要播放隨機播放歌曲,而不是所有的人:

from glob import glob 
import random 

filenames = glob('./music/*.mp3') 
playmusic(random.choice(filenames)) 
+1

感謝。它適用於這兩種解決方案。 你能幫助多一點嗎? 如何從目錄中選擇一個隨機文件? 通過傳遞playmusic(隨機(文件名))? –

+0

很高興 - 如果您想播放隨機文件而不是所有文件,請使用我添加到第二次編輯的代碼 – jfbeltran

+0

豎起大拇指。現在工作正常。 –

相關問題