pythonpygamemixer

Pygame Mixer music (multiple music tracks)


I have a quite simple question but surprisingly did not find a duplicate.

I have 2 music tracks for my game and want to switch fom the first music to something else before it runs out naturally.

mixer.music.load('music.mp3')
mixer.music.queue("music_phase2.mp3")
mixer.music.play(1, 0.0, 3000)

Normally i can use music.queue to go to the next music track. But i want the first music to stop after a specific event (like a timer or counter) and immediately start the next track.

I thought of something like this but it didnt work. (I need to mention that in my program i want to load the music within a while loop so maybe that is causing problems.) This part of the code handles the music. The first music stops as it should afte the counterr reaches 10. But the second music doesnt start to play (just silence).

from pygame import mixer
pygame.mixer.init()

running = True

mixer.music.load('music.mp3')
mixer.music.play(1, 0.0, 3000)

# main loop
while running:
    if logic.counter > 10:
        mixer.music.stop()
        mixer.music.unload()
        mixer.music.load('music_phase2.mp3')
        mixer.music.play(1, 0.0, 3000)


#code doesnt end here but the rest shouldnt influence the music

Solution

  • I found your mistake. You are doing:

    while running:
        if logic.counter > 10:
            mixer.music.stop()
            mixer.music.unload()
            mixer.music.load('music_phase2.mp3')
            mixer.music.play(1, 0.0, 3000)
    

    The problem is, the logic.counter keeps increasing! I don't see anywhere a flag or something inside the code that is supposed to stop the logic.counter from increasing!

    This means that once the logic.counter reaches 11, it enters the if block. However, it will enter the if when it is 12 and re-load the music again. and again, and again. Forever. You need to change it to:

        if logic.counter == 10:
    

    So it will unload the first music and load the second music only once.