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
竖起大拇指。现在工作正常。 –