Pygame cannot open sound file

2019-04-29 09:17发布

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!

6条回答
ら.Afraid
2楼-- · 2019-04-29 09:57

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

查看更多
smile是对你的礼貌
3楼-- · 2019-04-29 09:58

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楼-- · 2019-04-29 10:04

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.

查看更多
相关推荐>>
5楼-- · 2019-04-29 10:15

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楼-- · 2019-04-29 10:19

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.

查看更多
在下西门庆
7楼-- · 2019-04-29 10:19

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

查看更多
登录 后发表回答