简体   繁体   中英

Cannot open audio file in the directory

I have following code which I'm using to play music from the given folder. The problem is: Porgram can't open the file

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")

It gives me following error:

 pygame.error: Couldn't open '1.mp3'

When I remove the for loop in try block and write filename = "music/1.mp3" Program runs it without a problem.The error trackback leads to playmusic(filename) and pygame.mixer.music.load(soundfile) . But I'm unable to figure out what I'm doing wrong here. Anyone?

os.listdir() does not give you the full path for the file, so it won't include the ./music/ part of the path. You could simply change the line to:

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

Or even better, use os.path to avoid odd behavior

EDIT: This is actually a great use case for glob! You can use a wildcard to grab all mp3 files inside the music folder. Glob also returns the full path of the files ( ./music/song1.mp3 ) instead of the raw filenames ( song1.mp3 ).

from glob import glob

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

EDIT 2 : To play a random song instead of all of them:

from glob import glob
import random

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM