How can I set a Timer to control a function call inside a loop?

81 Views Asked by At

I have this function, which plays Spotify:

#a function to play Spotify
def play(id_):
    print 'playing', id_
    os.system("osascript -e 'tell application \"Spotify\" to play track \"%s\"'" % (id_,))

and the following loop, which iterates through all playlist songs, obtains all playable id's (foreign_id), passing them to play(id_),

and passes each song duration to time.sleep() to halt the loop until each song finishes, repeating the loop all over again:

for i, song in enumerate(song_playlist):
            #we need to track each song id
            song_id = song_playlist[i]['id']
            #in order to get song 'duration', access 'song/profile response' and pass the id as an argument
            response_profile = en.get('song/profile', id=song_id, bucket="audio_summary")
            song_profile = response_profile['songs']
            dur = song_profile[0]['audio_summary']['duration']
            #convert to miliseconds     
            dur *= 1000
            print int(round(dur))                           
            #now we access each song 'foreign_id' 
            for track in song:
                track = song['tracks'][i]
                track_id = track['foreign_id'].replace('-WW', '')           
            print '{0} {2} {1}'.format(i, song['artist_name'], song['title'])
            #call the function for each track
            play(track_id) #CALL FUNCTION HERE
            time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION

however, only one song plays, and recursion dies out.

how can I correct the code so I can have the function playing all tracks in sequence running the code only once?

1

There are 1 best solutions below

0
On

It looks like play(track_id) should be inside the for track in song loop. You need to indent it 1 level.

for i, song in enumerate(song_playlist):
    # Code as before ...
    for track in song:
        track = song['tracks'][i]
        track_id = track['foreign_id'].replace('-WW', '')           
        print '{0} {2} {1}'.format(i, song['artist_name'], song['title'])
        play(track_id) #CALL FUNCTION HERE
    time.sleep(int(round(dur))) # SET INTERVAL CALL TO EACH SONG DURATION