Python Forum

Full Version: How to loop music with pygame
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have this line of code below:

pygame.mixer.Channel(0).play(pygame.mixer.Sound("Z:\Finley\School\Sixth Form\CS\Code\OOP\dice_gamble_home_music.mp3"))
How would I get this music to loop forever?
From pygame docs
Have a list of tracks and replay them indefinitely.
Some psuedocode of python doing this process in a game I made that repeated songs

https://github.com/metulburr/pong/blob/m...classic.py

class Music:
    def __init__(self, volume):
        self.path = os.path.join('resources', 'music')
        self.setup(volume)

        
    def setup(self, volume):
        self.track_end = pg.USEREVENT+1
        self.tracks = []
        self.track = 0
        for track in os.listdir(self.path):
            self.tracks.append(os.path.join(self.path, track))
        random.shuffle(self.tracks)
        pg.mixer.music.set_volume(volume)
        pg.mixer.music.set_endevent(self.track_end)
        pg.mixer.music.load(self.tracks[0])
In the event loop to replay if track is over, switch to the next which could be itself if there is only one song in the list
        if event.type == self.background_music.track_end:
            self.background_music.track = (self.background_music.track+1) % len(self.background_music.tracks)
            pg.mixer.music.load(self.background_music.tracks[self.background_music.track]) 
            pg.mixer.music.play()