I have the following Code
def play_music():
song = playlist.get(ACTIVE)
next_one = playlist.curselection()
next_one = next_one[0] 1
pygame.mixer.music.load(song)
pygame.mixer.music.play(loops=0)
pygame.mixer.music.set_endevent()
for event in pygame.event.get():
playlist.selection_clear(0,END)
playlist.activate(next_one)
playlist.select_set(next_one,last=None)
song = playlist.get(ACTIVE)
pygame.mixer.music.queue(song)
When I run the Code, then it plays a song and after that it plays the next song in the playlist. But I want to implement this into a loop. It should queue the next song, as much songs it has in the playlist (i.e: I have 5 songs in the playlist, then I want, that I only have to press the Play-Button once and after that it plays all 5 songs, one by one.)
A Picture of my Program: https://i.stack.imgur.com/T5Gch.png I hope you can help me. Thank you for your help in advance.
CodePudding user response:
Here is example from my answer for Utilising the pygame.mixer.music.get_endevent()
It creates own event MUSIC_END
and assing it to music endevent.
Later it loads one song and adds next song to queue.
When first song will finished then it will generate/send event MUSIC_END
. But this need to run all time for event in pygame.event.get()
to catch this event and run code which will add next song to queue.
When it will finish next song then it will generate/send again event MUSIC_END
which loop will catch and add again song to queue.
With more songs it need to keep all songs on list and remeber which song from list it has to add to queue.
EDIT:
Version which works with list of songs and changes also text on label.
import pygame
import tkinter as tk
def check_event():
global current_song
global next_song
for event in pygame.event.get():
if event.type == MUSIC_END:
print('music end event')
# calculate index for current song (which was takes from queue)
#current_song = (current_song 1) % len(songs)
current_song = next_song
# add title for current song
label['text'] = songs[current_song]
# calculate index for next song
next_song = (current_song 1) % len(songs)
# add to queue next song
pygame.mixer.music.queue(songs[next_song])
# run again after 100ms (0.1s)
root.after(100, check_event)
def play():
label['text'] = songs[current_song]
pygame.mixer.music.play()
# --- main ---
songs = [
'audio1.wav',
'hello-world-of-python.mp3',
]
current_song = 0
next_song = 1
pygame.init()
# define new type of event
MUSIC_END = pygame.USEREVENT 1
# assign event to `endevent`
pygame.mixer.music.set_endevent(MUSIC_END)
# play first song
pygame.mixer.music.load(songs[current_song])
# calculate index for next song
next_song = (current_song 1) % len(songs)
# add to queue next song
pygame.mixer.music.queue(songs[next_song])
root = tk.Tk()
label = tk.Label(root)
label.pack()
button = tk.Button(root, text='Play', command=play)
button.pack()
check_event()
root.mainloop()
pygame.quit()