尝试使用 pygame 添加声音时出现错误。 我已将所有 .wav 文件与我的 python 脚本放在同一目录中。 这是我第一次使用 pygame,所以我一无所知。
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()
这是我得到的:
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]
请您参考如下方法:
该文件不必与 python 文件位于同一目录中,但必须位于应用程序的工作目录中。
差异可以通过以下方式调查:
import os
currentWorkDir = os.getcwd()
print(currentWorkDir)
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
print(sourceFileDir)
另见 Import-related module attributes .
应用程序可以更改当前工作目录,使其与 python 源文件目录相同:
import os
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir)
