Pygame : force playing next song in queue even if actual song isn't finished? (aka "Next" button)

Question:

I want to make with pygame the same functionalities as a walkman : play, pause , queuing is ok.But how to do the previous/next buttons?

How can I ,with pygame, force the play of the next song which has been queued (and pass the ong which is actually playing?)

Answers:

Have a list of song titles, and keep track of where you are in the list with a variable. Whether you are using pygame.mixer.music or pygame.mixer.Sound, when the “next” button is clicked, just have the variable change by one, and then stop the song, and have song the variable corresponds to play instead.

Code example for pygame.mixer.Sound:

#setup pygame above this
#load sounds
sound1 = pygame.mixer.Sound("soundone.ogg")
sound2 = pygame.mixer.Sound("soundtwo.ogg")

queue = [sound1, sound2] #note that the list holds the sounds, not strings
var = 0

sound1.play()

while 1:
    if next(): #whatever the next button trigger is
        queue[var].stop() # stop current song
        if var == len(queue - 1): # if it's the last song
            var = 0 # set the var to represent the first song
        else:
            var += 1 # else, next song
        queue[var].play() # play the song var corresponds to
Answered By: makeworld

This was an example i got working for myself to wrap my head around the behavior of the program.

from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'  # noqa This is used to hide the default pygame import print statement.
import pygame
import time

# Credit: https://forums.raspberrypi.com/viewtopic.php?t=102008

pygame.mixer.init()
pygame.display.init()

screen = pygame.display.set_mode((420, 240))  # Shows PyGame Window.

playlist = list()
playlist.append('/Music/Tom MacDonald - Angels (Explicit).mp3')
playlist.append('/Music/Falling In Reverse - Bad Girls Club (Explicit).mp3')

pygame.mixer.music.load(playlist.pop())               # Get the first track from the playlist
pygame.mixer.music.queue(playlist.pop())              # Queue the 2nd song
pygame.mixer.music.set_endevent(pygame.USEREVENT)     # Setup the end track event
pygame.mixer.music.play()                             # Play the music

running = True
while running:
    time.sleep(.1)
    for event in pygame.event.get():
        if event.type == pygame.USEREVENT:                # A track has ended
            if len(playlist) > 0:                         # If there are more tracks in the queue...
                pygame.mixer.music.queue(playlist.pop())  # Queue the next one in the list
        elif event.type == pygame.QUIT:                   # Create a way to exit the program.
            running = False

Answered By: JayRizzo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.