尝试使用 pygame 创建声音时出错 [英] I've got an error when trying to create sound using pygame

查看:76
本文介绍了尝试使用 pygame 创建声音时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用 pygame 添加声音时遇到错误.我已将所有 .wav 文件与 python 脚本放在同一目录中.这是我第一次使用pygame,所以我一无所知.

导入pygamepygame.init()pygame.mixer.init()尝试:person_sound = pygame.mixer.Sound("person.wav")pygame.mixer.Sound.play(person_sound)除了:导入回溯traceback.print_exc()

这是我得到的:

<块引用>

pygame 1.9.5来自 pygame 社区的您好.https://www.pygame.org/contribute.html回溯(最近一次调用最后一次):文件G:\Desktop\Sound Test\Sound-Test.py",第 7 行,在 <module> 中.person_sound = pygame.mixer.Sound("person.wav")FileNotFoundError: 没有这样的文件或目录.[1.345s内完成]

解决方案

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

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

import oscurrentWorkDir = 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:\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]

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)

这篇关于尝试使用 pygame 创建声音时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆