Python Forum
[PyGame] How to loop music with pygame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] How to loop music with pygame
#1
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?
"Only Boring People Get Bored"
Reply
#2
From pygame docs
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
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()
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with music - Pygame.error GaseBall 1 3,190 Nov-28-2019, 07:46 PM
Last Post: SheeppOSU
  How can I make music with python/pygame? xBlackHeartx 12 7,183 Oct-15-2019, 08:00 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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