且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试使用 pygame 创建声音时出现错误

更新时间:2023-02-22 17:47:05

该文件不必与 python 文件在同一目录中,但必须在应用程序的工作目录中.

可以通过以下方式调查差异:

import os当前工作目录 = os.getcwd()打印(当前工作目录)sourceFileDir = os.path.dirname(os.path.abspath(__file__))打印(源文件目录)

另见导入相关模块属性一>.

应用程序可以更改当前工作目录,使其与python源文件目录相同:

导入操作系统sourceFileDir = os.path.dirname(os.path.abspath(__file__))os.chdir(sourceFileDir)

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:DesktopSound TestSound-Test.py", line 7, in <module>
    person_sound = pygame.mixer.Sound("person.wav")
FileNotFoundError: No such file or directory.
[Finished in 1.345s]

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)