Yashasvi Bhatt
Yashasvi Bhatt

Reputation: 324

Loop over a list containing path to sound files

So what I was planning to do was loop over a list which contains path to my sound files and play them using pygame.mixer module in python, but when I did this the problem I encountered was pygame always play the last most index path file from the list, and rest were skipped. Example if my list contains 2 items:

music_list = ['abc.mp3', 'gef.mp3']
for music_index in range(len(music_list)):
    mixer.init()
    mixer.music.load(music_list[music_index])
    mixer.music.play()

then it never plays abc.mp3 file and directly plays the last file gef.mp3

Upvotes: 1

Views: 683

Answers (3)

Rabbid76
Rabbid76

Reputation: 211277

Use pygame.mixer.music.queue() to load sound files and queue it:

mixer.init()
mixer.music.load('abc.mp3')
mixer.music.play()
mixer.music.queue('gef.mp3')

Upvotes: 1

Taek
Taek

Reputation: 1024

You don't need to use a range to iterate over items of a list in python, simply using:

for music in music_list:
     ...
     mixer.music.load(music)
     ...

will do the trick.

As per why your code does'nt work it's most likely because you can't play two songs at the same time so the last song is played "over" the first ones.

Upvotes: 1

larticho
larticho

Reputation: 169

I think it's because play() method does not bloc your code, so your code will continue once you have lauched the music. Therefore, you will start to play the first music and immediately after, you will launch the second one. You end up skipping all the musics, and only playing the last one.

Upvotes: 1

Related Questions