Trying to loop through a music playlist

I have been trying to create a function that loops through a list containing the paths to 2 songs and plays each song one after another and repeats this process, basically just playing the playlist on repeat.

from direct.showbase.ShowBase import ShowBase
from panda3d.core import *


class Main(ShowBase):
    def __init__(self):
        super().__init__()
        self.music = ["models/Music/AOT.mp3", "models/Music/KNY.mp3"]
        self.play_song = True
        self.taskMgr.add(self.music_task, "music-task")

    def music_task(self, task):
        for song in self.music:
            if self.play_song:
                self.current_song = self.loader.loadMusic(song)
                self.current_song.play()
                self.current_song.setPlayRate(2)
                self.play_song = False
            if self.current_song.getTime() < self.current_song.length():
                self.play_song = False
            else:
                self.play_song = True
        return task.cont


base = Main()
base.run()

Above is the code I have so far. The issue with this is that it plays the first song then the next but instead of playing the first sing again it just plays the second song on repeat. Any Help is appreciated :pray: :pray:

You just need to increase the index at the end of the song, check that it does not exceed the range and play another song. Something like this.

from direct.showbase.ShowBase import ShowBase
from panda3d.core import *


class Main(ShowBase):
    def __init__(self):
        super().__init__()
        self.music_list = [self.loader.loadMusic("models/Music/AOT.mp3"), self.loader.loadMusic("models/Music/KNY.mp3")]
        self.music_active = 0
        self.play_song = False

        self.taskMgr.add(self.music_task, "music-task")

        self.my_play(0)

    def my_play(self, number):
        self.music_list[number].play()
        self.music_active = number
        self.play_song = True
        print(self.music_list[number].getName())

    def music_task(self, task):
        if self.music_list[self.music_active].status() == 1:
            if self.play_song == True:
                self.play_song = False
                if self.music_active < len(self.music_list)-1:
                    self.music_active += 1
                else:
                    self.music_active = 0

                self.my_play(self.music_active)

        return task.cont


base = Main()
base.run()
3 Likes

Thank you very much that works perfectly :))