简体   繁体   中英

Pygame error: not able to open .wav file

I have a problem with my Pygame program. I need help. The wav file is in the same directory as the python file. I run It in terminal- Python3:

import pygame.mixer
sounds = pygame.mixer
sounds.init()

def wait_finish(channel):
    while channel.get_busy():
        pass

asked = 0
true = 0
false = 0

choice = str(input("Push 1 for true, 2 for false, 0 to end"))
while choice != '0':
      if choice == '1':
             asked = asked + 1
             true = true + 1
             s = sounds.Sound("correct.wav")
             wait_finish(s.play())
      if choice == '2':
             asked = asked + 1
             false = false + 1
             s = sounds.Sound("wrong.wav")
             wait_finish(s.play())
      choice = str(input("Push 1 for true, 2 for false, 0 to end"))

print ("you asked" +str(asked) + "questions")
print ("there were" +str(false) + "wrong answers")
print ("and" + str(true) + "correct answers")

It throws- pygame.error:

Unable to open file 'correct.wav'

I had the same problem, could not get this code to work:

correctSound = pygame.mixer.Sound('jingle3.wav')

I got pygame error:

Unable to open file 'jingle3.wav'

The problem was solved by loading the 'jingle3.wav' into Audicity and changing it from 32-bit PCM to a 16-bit PCM .wav-file. After that the pygame.mixer.Sound worked perfectly.

I got this tip on this forum, and it worked!

Rather than have a discussion in the comments section I'll post this.
Once def wait_finish(channnel): has been altered to def wait_finish(channel): and the issue with sounds.Sound rather than sounds.Sounds has been resolved, the program works fine with normal .wav files on my machine.
I am convinced that the error of Sound or Sounds for calling the wrong.wav file to be played would explain the "unable to open file wrong.wav" message.
If pygame doesn't like something about the file it may well not play it and this is where a line like:

sounds.pre_init(frequency=22050, size=-16, channels=2, buffer=4096)

(called before sounds.init() ) might come into play.
(NB you might have to use a different buffer option as I am testing with pygame for python 2.7)

On my box, if pygame doesn't like or cannot find the file, I get no error at all but the speakers click when the call to play is made.
All I can suggest at this point is that you try an entirely different wav file to the current one you are using for wrong answers and see if it makes a difference. Just for the record, I changed your wait_finish function to :

def wait_finish(channel):
    while channel.get_busy():
        pygame.time.Clock().tick(10)

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