Loop over a list containing path to sound files [duplicate]

会有一股神秘感。 提交于 2021-01-29 21:10:29

问题


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


回答1:


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')



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/63488105/loop-over-a-list-containing-path-to-sound-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!