无法在目录中打开音频文件

时间:2017-09-22 18:02:18

标签: python pygame

我有以下代码,我用它来播放给定文件夹中的音乐。 问题是: 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循环并写入 filename =“music / 1.mp3”程序运行它没有问题。错误引用导致< strong> playmusic(filename) pygame.mixer.music.load(soundfile) 。但我无法弄清楚我在这里做错了什么。 任何人吗?

1 个答案:

答案 0 :(得分:2)

os.listdir()没有为您提供该文件的完整路径,因此它不会包含路径的./music/部分。您只需将该行更改为:

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

甚至更好,使用os.path来避免奇怪的行为

编辑:这实际上是glob的一个很好的用例!您可以使用通配符来获取音乐文件夹中的所有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))