play random music but without repeating and at the end of the song start next

Viewed 44

I am writing to ask you, I have my code that plays songs randomly when you press a button, but how can I make the songs not repeat themselves and when one ends, the next starts?

def play_music():

        songs = ("sonidos/playlist/cant toch this.mp3", 
        "sonidos/playlist/hey song.mp3",
        "sonidos/playlist/i like to move it.mp3",
        "sonidos/playlist/lets go.mp3",
        "sonidos/playlist/little bit.mp3",
        "sonidos/playlist/ohohoho.mp3",
        "sonidos/playlist/pump it up.mp3",
        "sonidos/playlist/pump up the jum.mp3",
        "sonidos/playlist/seven nation army.mp3",
        "sonidos/playlist/ready for this.mp3",
        "sonidos/playlist/seven nation army.mp3",
        "sonidos/playlist/usher yeah.mp3",
        "sonidos/playlist/what is love.mp3")
        
        selected_song = random.choice(songs)   
        pygame.mixer.music.load(selected_song) 
        pygame.mixer.music.play() 

1 Answers

You can use random.shuffle() to randomize the song list and play the songs in the randomized list one by one.

Below is the modified play_music():

def play_music():
    # songs need to be a list instead of tuple if random.shuffle() is used
    songs = [
        "sonidos/playlist/cant toch this.mp3",
        "sonidos/playlist/hey song.mp3",
        "sonidos/playlist/i like to move it.mp3",
        "sonidos/playlist/lets go.mp3",
        "sonidos/playlist/little bit.mp3",
        "sonidos/playlist/ohohoho.mp3",
        "sonidos/playlist/pump it up.mp3",
        "sonidos/playlist/pump up the jum.mp3",
        "sonidos/playlist/seven nation army.mp3",
        "sonidos/playlist/ready for this.mp3",
        "sonidos/playlist/seven nation army.mp3",
        "sonidos/playlist/usher yeah.mp3",
        "sonidos/playlist/what is love.mp3"
    ]

    # randomize the song list
    random.shuffle(songs)
    # play the songs in the list one by one
    for song in songs:
        print(f"playing '{song}' ...")
        pygame.mixer.music.load(song)
        pygame.mixer.music.play()
        # wait until the song completes
        while pygame.mixer.music.get_busy():
            pass

Note that a simple for loop is used to play the songs one by one. If you want to integrate into tkinter application, you may need to use other logic.

Related