Search code examples
pythonaudiopygamemedia-player

python - pygame audio player. Get end of the song to play the next in line


I'm stuck with my python audio player. What I want to do is to get the event when the song is over, so that I can play the next song in line. I can switch the playlist folder and play one song. But how can I switch to the next one?

Here is the code:

import pygame
from pygame.locals import *
import os
import sys
import random
import re

play_stereo = True
songNumber = 0
x = 0
SONG_END = pygame.USEREVENT + 1

pygame.display.set_caption("Pygame Audio player")
screen = pygame.display.set_mode((800, 800), 0, 32)
pygame.init()

def build_file_list():
    file_list = []
    for root, folders, files in os.walk(folderPath):
        folders.sort()
        files.sort()
        for filename in files:
            if re.search(".(aac|mp3|wav|flac|m4a|pls|m3u)$", filename) != None: 
                file_list.append(os.path.join(root, filename))
    return file_list

def play_songs(file_list):
    random.shuffle(file_list)
    pygame.mixer.music.load(file_list[songNumber])
    pygame.mixer.music.play(1)

while True:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_q:
                folderPath = "/Users/dimitristeinel/Documents/git projects/pygame audioplayer/playlist1"
                files = build_file_list()
                play_songs(files)

            if event.key == K_w:
                folderPath = "/Users/dimitristeinel/Documents/git projects/pygame audioplayer/playlist2"
                files = build_file_list()
                print(files)

            if event.key == K_ESCAPE:
                sys.exit()
                break

I really hope someone can help. Thanks in advance...


Solution

  • Use pygame.mixer.music.queue.

    It queues up a song which will begin playing after the first one is finished:

    def play_songs(file_list):
        random.shuffle(file_list)
        pygame.mixer.music.load(file_list[songNumber])
        pygame.mixer.music.play(1)
    
        for num, song in enumerate(file_list):
            if num == songNumber:
                continue # already playing
            pygame.mixer.music.queue(song)