简体   繁体   中英

PyGame: Unable to open file

I'm trying some basic examples from the Making Games with Python & Pygame book, but I'm facing a weird problem. Here is the example source:

import pygame, time

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

This source produces the following error:

Traceback (most recent call last): File "C:/Users/Thiago/PycharmProjects/PyGame/Sound/app.py", line 3, in soundObj = pygame.mixer.Sound('beep.wav') pygame.error: Unable to open file 'beep.wav'

The beep.wav file is properly saved on the same folder of my Python script. I've tried the os.listdir() command and it returns the wav file. Is there any issue, known bug or am I doing something wrong?

Here is my environment:

  • Windows 10 64 bits
  • Python 3.4
  • Pygame 1.9

You have to initialize the module or all of the pygame first. There is an pygame_init() initializer that is going to help you with that. You can find it here

I solved this problem adding the pygame.init() to initialize the Pygame and pygame.display.set_mode() to create the window.

import pygame, time

pygame.init() # initialize the pygame
soundObj = pygame.mixer.Sound('beep.wav')
DISPLAYSURF = pygame.display.set_mode((400, 300)) # create the game window
soundObj.play()
time.sleep(1) # wait and let the sound play for 1 second
soundObj.stop()
brew install libogg
brew install libvorbis
brew install sdl_mixer --with-libvorbis
brew reinstall sdl_mixer --with-libvorbis

this function for me :D

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