简体   繁体   English

Pygame转成.exe后无法打开声音文件

[英]Pygame cannot open sound file after being converted to .exe

So I have a game I've written in pygame.所以我有一个我用 pygame 编写的游戏。 It works great.它工作得很好。 I love it.我喜欢它。 I want to share it with my friends, so I tried compiling it into an exe.我想和我的朋友分享,所以我试着把它编译成一个exe。 This is where things took a dive.这是事情发生的地方。

Here's a sample of my code:这是我的代码示例:

import os, sys, csv
import pygame
import random
import subprocess

pygame.mixer.init(22050, -16, 2, 256)
pygame.init()

clock = pygame.time.Clock()
width   = 1080
height  = 1080
keys    = pygame.key.get_pressed()
size    = (width, height)
myfont  = pygame.font.Font('8Bit.ttf', 30)
screen  = pygame.display.set_mode([width,height],pygame.FULLSCREEN) 
pygame.display.set_caption('My Game')

print(os.getcwd())
image   = pygame.image.load(os.path.join('image.png'))
engine  = pygame.mixer.Sound(os.path.join('engine.ogg'))
bang    = pygame.mixer.Sound('bang.ogg')

All my game files are in the same root directory as the game.我所有的游戏文件都和游戏在同一个根目录下。 And again, it runs fine when I just run the python code from the terminal.同样,当我从终端运行 python 代码时,它运行良好。

I converted it using pyinstaller and have it installed to a directory and all the game files are imported to that directory.我使用 pyinstaller 对其进行了转换并将其安装到一个目录中,并且所有游戏文件都导入到该目录中。

The files are in the directory the print() call prints, and the error I get is:这些文件位于 print() 调用打印的目录中,我得到的错误是:

    pygame.error: Unable to open file 'engine.ogg'

I've tried including and removing the os.path.join() call, and even trying to just type out the entire path.我尝试包含和删除 os.path.join() 调用,甚至尝试只输入整个路径。

Any advice?有什么建议吗?

I use this with pyinstaller and it works great:我将它与 pyinstaller 一起使用,效果很好:

ROOT_DIR = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))

You need to define this variable in any.py file that's in your project's root folder.您需要在项目根文件夹中的 any.py 文件中定义此变量。 It'll now be the path to your project directory, no matter if the project is compiled or not.它现在将成为您的项目目录的路径,无论项目是否已编译。

Then you would use it like this:然后你会像这样使用它:

image = pygame.image.load(os.path.join(ROOT_DIR, 'image.png'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM