IsadeLuis
IsadeLuis

Reputation: 11

Pygame Mixer Initialization Issues

For this game I'm creating I need to use the pygame mixer. Here's how my code currently goes:

import pygame as pg
pg.init()
# Other stuff
class Menu(Scene):
    def __init__(self, screen, scenes):
        self.scenes  = scenes
        self.screen  = screen
        self.font    = pygame.font.SysFont('freesansbold.ttf', 32)
        self.music   = pygame.mixer.Sound("path to wav file")
        self.channel = pygame.mixer.Channel(0)
# Rest of code

However, every time I run that I get the following error:

pygame.error: mixer not initialized

So I tried to manually import the mixer with:

pygame.mixer.init()

but then I get the error:

pygame.error: ALSA: Couldn't open audio device: No such file or directory

Does anyone know how to fix this?

Upvotes: 1

Views: 3468

Answers (1)

Rabbid76
Rabbid76

Reputation: 211230

Every pygame module has to be initialized. You can either initialize all pygame modules with pygame.init() or each module separately. At least you need to call pygame.mixer.init.

The error message "pygame.error: ALSA: Couldn't open audio device: No such file or directory" means the the the file path used in pygame.mixer.Sound() is incorrect and the file does not exist at this location.
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory. The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script.
The name and path of the python file can be retrieved with __file__. The current working directory be changed with os.chdir(path).
Put the following at the beginning of your code to set the working directory to the same as the script's directory:

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))

If you are not sure about the current working directory, you can print it out:

print(os.getcwd())

Upvotes: 1

Related Questions