Python Forum
[PyGame] Music starts too early in state machine
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Music starts too early in state machine
#1
Hello,

Been working on a game using the template in the state machine tutorial, but I've run into a little problem with loading and running music.

Creating-a-state-machine


The problem is that when load the music in Game.load_data() but it starts playing the instant the program opens, not when I enter the Game state, which I would prefer. I'd like to put different music for the Game and Menu states.

class Control:
    def __init__(self):
        pg.mixer.pre_init(44100, -16, 1, 2048)
        pg.mixer.init()
        pg.init()

class Game(States):
    def __init__(self):
        States.__init__(self)
        self.next = 'menu'
        self.block_size = 50
        self.load_data()
        self.new()

    def load_data(self):
        pg.mixer.music.load(path.join(snd_dir, "spacelifeNo14.ogg"))
        pg.mixer.music.play(loops=-1)


This is every reference I have to music in there. Maybe my mixer.init() is in the wrong spot, but I wanted it there so it works for the Game and the Menu
Reply
#2
Quote:
    def load_data(self):
        pg.mixer.music.load(path.join(snd_dir, "spacelifeNo14.ogg"))
        pg.mixer.music.play(loops=-1)
Your music loads and plays immediately because the method load_data() in the dunder init method and play() is in load_data(). So when the class is created it starts playing the music instead of when the state starts. That is why in the example there is a startup/cleanup methods for entering the state and exiting the state. Control runs these method directly when switching states.
control
    def change_state(self):
        if self.state.done:
            self.state.cleanup()
            self.state_name = self.state.next
            self.state.done = False
            self.state = self.state_dict[self.state_name]
            self.state.startup()
one state
class Menu(States):
    def __init__(self):
        ...
    def cleanup(self):
        print('cleaning up Menu state stuff')
    def startup(self):
        print('starting Menu state stuff')
Here is a pong game using the state machine that starts music when the game state starts, and stops when it exits back to the main menu.

You also dont need pygame.mixer.init() at all as pygame.init() does that already. You only need that if you do not have a display such as using pygame as a music player only.
Recommended Tutorials:
Reply
#3
Thank-you. That seems really obvious. No idea why I didn't see that. I'm kinda dumb sometimes lol.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Creating multiple instances in State Machine. michael1789 0 1,778 Dec-21-2019, 12:50 AM
Last Post: michael1789

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020