pythonjsonspotifyspotipy

Spotipy Current Track Data - Getting current track ID


I don't see a whole lot of info on current_user_playing_track() for Spotipy so hoping someone will be able to help me on this.

import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
import json
import requests

cid = 'my client id'
secret = 'my client secrets'
redirect_uri = 'http://localhost:7777/callback'
username = 'my username'
scope = 'user-read-currently-playing'
token = util.prompt_for_user_token(username, scope, cid, secret, redirect_uri)
spotify = spotipy.Spotify(token)

def get_current_song():
    # Get track information
    track = spotify.current_user_playing_track()
    print(json.dumps(track, sort_keys=True, indent=4))
    artist = json.dumps(track['item']['album']['artists'][0]['name'])
    track = json.dumps(track['item']['name'])

    return artist, track

def main():
    artist, track = get_current_song()
    if artist !="":
        print("Currently playing " + artist + " - " + track + "--TRACK ID--")

if __name__ == '__main__':
    main()

This works with no trouble, but I want the track ID so I can make another function to analyze the audio but when I add this

def get_current_song():
    # Get track information
    track = spotify.current_user_playing_track()
    print(json.dumps(track, sort_keys=True, indent=4))
    artist = json.dumps(track['item']['album']['artists'][0]['name'])
    track = json.dumps(track['item']['name'])
    track_id = json.dumps(track['item']['id'])
    return artist, track

I get this error

Traceback (most recent call last):
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Projects\spotipy\kasify.py", line 32, in <module>
    main()
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Projects\spotipy\kasify.py", line 27, in main
    artist, track = get_current_song()
                    ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Projects\spotipy\kasify.py", line 23, in get_current_song
    track_id = json.dumps(track['item']['id'])
                          ~~~~~^^^^^^^^
TypeError: string indices must be integers, not 'str'

Solution

  • I fixed your code and I deleted unnecessary stuff.

    import spotipy
    from spotipy.oauth2 import SpotifyOAuth
    from pprint import pprint
    
    cid = 'my client id'
    secret = 'my client secrets'
    redirect_uri = 'http://localhost:7777/callback'
    scope = 'user-read-currently-playing'
    
    spotify = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=cid,
                                                   client_secret=secret,
                                                   redirect_uri=redirect_uri,
                                                   scope=scope))
    
    def get_current_song():
        # Get track information
        track = spotify.current_user_playing_track()
        pprint(track)
        artist = track["item"]["artists"][0]["name"]
        t_name = track["item"]["name"]
        t_id = track["item"]["id"]
        return artist, t_name, t_id
    
    def main():
        artist, track, tid = get_current_song()
        if artist !="":
            print(f"Currently playing {artist} - {track} - {tid}")
    
    if __name__ == '__main__':
        main()