Pygame cannot open sound file after being converted to .exe

Viewed 154

So I have a game I've written in pygame. It works great. I love it. I want to share it with my friends, so I tried compiling it into an 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.

I converted it using pyinstaller and have it installed to a directory and all the game files are imported to that directory.

The files are in the directory the print() call prints, and the error I get is:

    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.

Any advice?

1 Answers

I use this with pyinstaller and it works great:

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. 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'))
Related