当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Including sound files in a pygame script using pyinstaller

问题描述:

I am new to programming, so I made myself the challenge to create Pong, and so I did. Now I want to share it with a couple of friends, so I decided to try using pyinstaller (have tried cx_Freeze).

In this Pong game I have 3 sound effects, located in the folder "sfx". So I've looked into including files using pyinstaller, so my .spec file says:

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,

and in the Pong program itself, I use this code to get the path:

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)

So I make the exe file using pyinstaller (with the command pyinstaller pong.spec)

but when I open the pong.exe file the command window says:

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

but in that exact same path is hitPaddle.ogg

It seems to me that pygame isn't able to found it for some weird reason?

Thanks

Sisoma Gmo Munden

网友答案:

I believe the issue is in this line. You are not refrencing the files correctly. You wrote:

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

Instead you should of just:

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

This is because when you added the files in the spec file, you stated that they should be in "root\sfx" folder. When the .exe is run in onefile mode, all files are actually located in a temp folder called MEIXXXX, with XXXX being some integers. When you run the .exe, if you open this folder you should be able to see your files there.

分享给朋友:
您可能感兴趣的文章:
随机阅读: