Pygame cannot open sound file

2019-04-29 10:05发布

问题:

import pygame, time
from pygame.locals import *

soundObj = pygame.mixer.Sound('beeps.wav')
soundObj.play()

time.sleep(1) # wait and let the sound play for 1 second
soundObj.stop()

and it throws this error:

Traceback (most recent call last):
  File "C:/Users/Jauhar/Desktop/Python/sounds.py", line 4, in <module>
    soundObj = pygame.mixer.Sound('beeps.wav')
pygame.error: Unable to open file 'beeps.wav'

The beeps.wav file is saved in the same directory as the python file the code is in.

I can't understand why it won't work!

回答1:

You cannot use pygames' library's unless you initialize either the modules your using or all of pygame.

    pygame.mixer.pre_init(44100, 16, 2, 4096) #frequency, size, channels, buffersize
    pygame.init() #turn all of pygame on.

do these before you do anything in pygame. I recommend it.



回答2:

Pygame (version 2.9 at least) doesn't support 32-bit float WAVs. Re-encode it to a signed 16-bit WAV (using Audacity for example).



回答3:

Try logging this information, and you may find your problem.

import os
os.getcwd() # Log this line.
soundObj = pygame.mixer.Sound('beeps.wav')

This should tell you what directory your application is looking in when trying to access your sound file. You'll probably find it's at the base of your game directory.



回答4:

Having a similar problem, I found that the size of the .wav file had a bearing on the problem. Making the .wav file smaller enabled it to work without making major modifications to the problem



回答5:

The same program works for me if I create a display surface before playing the sound.

    #! Python 3
'''
Making games with python chapter 2 program 5
'''
import pygame, sys, time
from pygame.locals import*

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Sound!!")

soundObj = pygame.mixer.Sound('badswap.wav')
soundObj.play()
time.sleep(1) #wait and let the sound play for X second
soundObj.stop()

while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()


回答6:

Have the sound file after pygame.init(). I had this problem but after placing the sound file after that it worked just fine for me.