[PyGame] How to loop music with pygame - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Game Development (https://python-forum.io/forum-11.html) +--- Thread: [PyGame] How to loop music with pygame (/thread-35353.html) |
How to loop music with pygame - finndude - Oct-23-2021 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? RE: How to loop music with pygame - menator01 - Oct-23-2021 From pygame docs RE: How to loop music with pygame - metulburr - Nov-09-2021 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/master/data/states/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() |