Search code examples
pythonjsonspotifyspotipy

Spotipy - Audio Analysis - Iterating Bars Start Time


I'm trying to iterate through the audio analysis bars and print on each beat.

def get_audio_data():
    artist, track, tid, progress = get_current_song()
    start = time.time()
    analysis = spotify.audio_analysis(tid)
    delta = time.time() - start
    # pprint(analysis) Print for debugging
    bpm = analysis["track"]["tempo"]
    bars = analysis["bars"]
    for bar in bars:
        for cds in bar:
            bst = bar["start"]
            for x in int(round(bst * 1000)):
                print(boom, x)
                while progress == boom:
                    print("BLEEP BLOOP!")
for x in int(round(bst * 1000)):
TypeError: 'int' object is not iterable
    'bars': [{
        'start': 0.36043,
        'duration': 1.37228,
        'confidence': 0.198
    }, {
        'start': 1.73271,
        'duration': 1.37925,
        'confidence': 0.462
    }, {
        'start': 3.11195,
        'duration': 1.38136,
        'confidence': 0.418
    }, {
        'start': 4.49331,
        'duration': 1.38127,
        'confidence': 0.761
    }

The current track position is in milliseconds but the beat start time is in seconds with 5 trailing decimal places. If I try to convert the variable bst into milliseconds it takes the entire list of numbers and adds them together then iterates them. So I'm left a list that contains all the same number instead of iterating through one and converting them separately. I've also tried to convert the progress time to seconds but I get it to track the progress as accurately as the beat is listed so the progress never == bar start time.


Solution

  • What you probably meant to do was

    for x in range(int(round(bst * 1000))):
        print(boom, x)
        while progress == boom:
            print("BLEEP BLOOP!")
    

    not

    for x in int(round(bst * 1000)):
        print(boom, x)
        while progress == boom:
            print("BLEEP BLOOP!")
    

    You can't iterate over an integer. Also, if you round a number, you don't need to turn it into an int. The ideal code is:

    for x in range(round(bst * 1000)):
        print(boom, x)
        while progress == boom:
            print("BLEEP BLOOP!")