Spotipy Current Track Data – Getting current track ID

Question:

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:UsersMeAppDataLocalProgramsPythonPython311Projectsspotipykasify.py", line 32, in <module>
    main()
  File "C:UsersMeAppDataLocalProgramsPythonPython311Projectsspotipykasify.py", line 27, in main
    artist, track = get_current_song()
                    ^^^^^^^^^^^^^^^^^^
  File "C:UsersMeAppDataLocalProgramsPythonPython311Projectsspotipykasify.py", line 23, in get_current_song
    track_id = json.dumps(track['item']['id'])
                          ~~~~~^^^^^^^^
TypeError: string indices must be integers, not 'str'
Asked By: error500

||

Answers:

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()
Answered By: Ximzend

@error500 sorry to bother, but how did you fix the string indices error?
(I know i shouldn’t be answering to ask but i have no reputation)

Answered By: user21398427
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.