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
#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


Messages In This Thread
RE: Music starts too early in state machine - by metulburr - Feb-27-2020, 11:44 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Creating multiple instances in State Machine. michael1789 0 1,801 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