Calling a function when MP3 ends in pygame Python 3.2.1 Windows

113 views Asked by At

I've hit a stand still in my python programming. Im looking at making a very basic GUI for a music player. I have got the program to play the sound, pause it and skip to next song but now i'm looking at implementing a function when a MP3 ends.

Simplifying my program for ease, I have:

import pygame as pg

pg.mixer.init()

def playNextSong():
    print("Playing next song")

pg.mixer.music.load('song.mp3')
pg.mixer.music.play()

I'm looking to call the playNextSong function when the MP3 ends.

I've tried this tutorial: http://www.nerdparadise.com/programming/pygame/part3

But I don't understand how to implement it.

Thanks for any advice.

Here's how

import pygame as pg
import random

pg.init() #init all pygame modules, rather than just the mixer. I assume
          #because you are getting that error that you are creating a
          #display as well.
SONG_END = pg.USEREVENT + 1
pg.mixer.music.set_endevent(SONG_END)
song_list = ['jazz.mp3', 'rock.mp3', 'metal.mp3', 'alt_rock.mp3']
current_song = random.choice(song_list)

def next():
    while True:
        next_song = random.choice(song_list)
        if current_song != next_song:
            return next_song

def play_song(next_song):
    pg.mixer.music.load(next_song)
    pg.mixer.music.play()
    print("Playing next song")


while True:
    for event in pg.event.get():
        if event.type == SONG_END:
            print("the song ended!")
            play_song(next())
0

There are 0 answers