Search code examples
pythoniospythonista

I want to play music in a loop


I make music player in Pythonista. A single mp3 file plays fine, but if I play multiple mp3 files, they all play at the same time.

Anyone has any idea?

This is my code:

import sound
import time
import glob

fileList = glob.glob("i7/*") #my folder

playerlist = []
for file in fileList:
    filename = file 
    sound.set_honors_silent_switch(False)
    sound.set_volume(1)

    player = sound.Player(filename) 
    playerlist.append(player)

for playerMin in playerlist:
    playerMin.play() #same time

Solution

  • From the docs, Player.play() just "Starts playing audio." If you want to play the song successively, you'll have to wait to play a song until the previous song ends because play does not block the main thread until the song is done playing.

    Try this:

    import sound
    import time
    
    ### Setup ###
    sound.set_honors_silent_switch(False)
    sound.set_volume(1)
    
    ### You populate this ###
    files = [...] 
    
    ### Play songs in order ###
    for filename in files:
        player = sound.Player(filename) 
        player.play()
        time.sleep(player.duration) # this is the key part –– makes the loop wait to play the next song until this song is done playing
        player.stop()
    

    This method is super flexible. For example, if you wanted to fade between songs you could ramp the volume while making the loop sleep for a little less than the song duration. That gets more complicated, but it's fundamentally done like this.