Home How can a looping pygame.mixer playlist be set playing in the background?
Reply: 1

How can a looping pygame.mixer playlist be set playing in the background?

BlandCorporation
1#
BlandCorporation Published in 2017-12-04 17:09:31Z

I've got a playlist of .ogg music files and I wanna set them playing in the game background on a big playlist loop. So, once all of the music files have been played by pygame.mixer, it loops back to the beginning to start again.

However, when I load the first track, set it playing and then add the other tracks to the queue, only the first track plays. I'm not sure how to get the queue to loop. What am I doing wrong?

playlist = ["2.ogg", "3.ogg", "1.ogg"]
pygame.mixer.init(frequency = 48000)
pygame.mixer.music.load("1.ogg")
pygame.mixer.music.play()
for track in playlist:
    pygame.mixer.music.queue(track)
furas
2#
furas Reply to 2017-12-04 18:40:59Z

I try to use queue() but it doesn't work for me.
Maybe it needs for event loop to work but it doesn't work for me too.

In documentation below queue() I found this comment:

This method only queues one music file.
If you call it and there already is a queued file, it will be overrided.

so queue is not so usefull.


I use pygame.mixer.music.set_endevent() with for event loop to start next track

import pygame

# define own event type
NEXT = pygame.USEREVENT + 1

playlist = [
    'track_one.ogg',
    'track_two.ogg',
    'track_three.ogg',
    'track_four.ogg',
]

tracks_number = len(playlist)
current_track = 0

pygame.init() # need it for event loop
#screen = pygame.display.set_mode((800,600)) # it can be useful to stop program 

pygame.mixer.init(frequency = 48000)

# start first track
pygame.mixer.music.load(playlist[current_track])
pygame.mixer.music.play()

# send event NEXT every time tracks ends
pygame.mixer.music.set_endevent(NEXT) 

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == NEXT:

            # get next track (modulo number of tracks)
            current_track = (current_track + 1) % tracks_number

            print("Play:", playlist[current_track])

            pygame.mixer.music.load(playlist[current_track])
            pygame.mixer.music.play()


pygame.quit()
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.312346 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO