使用pyinstaller在pygame脚本中包含声音文件

时间:2016-05-09 22:14:51

标签: python python-3.x pygame pyinstaller pong

我是编程新手,所以我自己创造了Pong的挑战,所以我做到了。现在我想和几个朋友分享,所以我决定尝试使用pyinstaller(尝试过cx_Freeze)。 在这个Pong游戏中,我有3个音效,位于文件夹" sfx"。所以我已经研究了使用pyinstaller包含文件,所以我的.spec文件说:

added_files = [
        ('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitOutline.ogg', 'sfx'),
        ('E:\Game Development Stuff\Python 3\Games\Pong\sfx\hitPaddle.ogg', 'sfx'),
        ('E:\Game Development Stuff\Python 3\Games\Pong\sfx/score.ogg', 'sfx')
        ]

a = Analysis(['pong.py'],
         pathex=['E:\\Game Development Stuff\\Python 3\\Games\\Pong'],
         binaries=None,
         datas=added_files,

并且在Pong程序本身中,我使用此代码来获取路径:

def resource_path(relative):
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, relative)
    return os.path.join(relative)

fileDir = os.path.dirname(os.path.realpath('__file__'))


hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))
hitOutline = resource_path(os.path.join(fileDir, "sfx", "hitOutline.ogg"))
score = resource_path(os.path.join(fileDir, "sfx", "score.ogg"))

hitPaddleSound=pygame.mixer.Sound(hitPaddle)
hitOutlineSound=pygame.mixer.Sound(hitOutline)
scoreSound=pygame.mixer.Sound(score)

所以我使用pyinstaller(使用命令pyinstaller pong.spec)制作exe文件 但是当我打开pong.exe文件时,命令窗口显示:

Traceback "<string>", Unable to open file 'E:\\Game Development Stuff\\Python 3\\Games\\Pong\\dist\\pong\\sfx\\hitPaddle.ogg'

但完全相同的路径是hitPaddle.ogg 在我看来,pygame是不是因为一些奇怪的原因而无法找到它?

由于 Sisoma Gmo Munden

2 个答案:

答案 0 :(得分:1)

我认为问题出在这一行。您没有正确地重新生成文件。你写道:

hitPaddle = resource_path(os.path.join(fileDir, "sfx", "hitPaddle.ogg"))

相反,你应该只是:

hitpaddle = resource_path("sfx\hitPaddle.ogg")

这是因为当您在spec文件中添加文件时,您声明它们应该位于&#34; root \ sfx &#34;夹。当.exe以onefile模式运行时,所有文件实际上都位于名为MEIXXXX的临时文件夹中,其中XXXX是一些整数。当您运行.exe时,如果您打开此文件夹,您应该能够在那里看到您的文件。

答案 1 :(得分:0)

在同一个问题上奋战了数小时之后,为我解决了问题。结论:

问题不在于无法找到它,而是说“找不到”。打开文件确实是一个问题。不知何故,.ogg格式出现了问题。我将所有.ogg文件都更改为.wav文件,并且我的游戏现在以可执行文件的形式运行而没有问题。

我不知道为什么,因为两个星期前,对于以前的版本,我确实使用完全相同的.ogg文件制作了一个可运行的.exe。而且我看不到所做的更改如何对此产生影响。无论如何,它现在可以工作,也许这也可以为其他人解决此问题。