Here is a short snippet from my code:
import pygame
class Player():
playlist= ["track1.mp3","track2.mp3",...]
def __init__(self):
pygame.init()
pygame.mixer.music.load(self.playlist[0])
pygame.mixer.music.play()
def playnext(self):
self.playlist = self.playlist[1:] + [self.playlist[0]]
pygame.mixer.music.load(self.playlist[0])
pygame.mixer.music.play()
My problem is that I want to play the next track after the first finished, but without a while true loop. This class is not the only one in my code and I want the others to work while the music plays.
Just like a trigger; when the song ends the playnext()
function is called.
Thanks in advance!
You can use
pygame.mixer.music.set_endevent
to make an event appear in the event queue when the music ends. Just check for that event and then change to the next song.The event will just be an integer (just like all other events) so in order to not shadow another event, use
pygame.USEREVENT
. If you have other user-defined events, just usepygame.USEREVENT + 1
, and thenpygame.USEREVENT + 2
and so on. Just make sure it's unique.Also, try not to put music in your player class; refactor it to another class. One class should preferably only do one thing. I created a short demonstration below. Everything underneath the line
if __name__ == '__main__':
could be the stuff in your other file.