I've got an error when trying to create sound

2019-07-18 04:00发布

问题:

I've got an error when trying to add a sound using pygame. I've put all of my .wav files in the same directory with my python script. This is my first time using pygame so I know completely nothing.

import pygame

pygame.init()
pygame.mixer.init()

try:
    person_sound = pygame.mixer.Sound("person.wav")
    pygame.mixer.Sound.play(person_sound)

except:
    import traceback
    traceback.print_exc()

Here is what I've got:

pygame 1.9.5
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
 File "G:\Desktop\Sound Test\Sound-Test.py", line 7, in <module>
    person_sound = pygame.mixer.Sound("person.wav")
FileNotFoundError: No such file or directory.
[Finished in 1.345s]

回答1:

The file doesn't have to be in the same directory as the python file, but it has to be in the working directory of the application.

The difference can be investigated by:

import os

currentWorkDir = os.getcwd()
print(currentWorkDir)

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
print(sourceFileDir)

See also Import-related module attributes.

The current working directory can be changed by the application, to be the same as the python source file directory:

import os

sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)


回答2:

Did you try giving the file with the full path? The error means it does not find the file.



标签: python pygame