loading...
Cover image for How to Play Spotify Songs and Show the Album Art using Spotipy Library and Python

How to Play Spotify Songs and Show the Album Art using Spotipy Library and Python

helloiamarra profile image Arra ・7 min read

Two days ago I mentioned in my previous post I was experimenting with the Spotipy libray and had struggles about how to use the library and what type of application I should make.

After digging around the docs and googling what type of projects you can make I found a very interesting project where you can make a Python script that shows the album art and play the song on Spotify using the terminal. So I decided to make my project.

Getting started

You first need to install Python to use the application. Go to Python Foundation and download and install Python. Follow the instructions given on the page and install it.

You also need to install the Spotipy library. To do this enter the following command in your terminal:

pip install spotipy

After you have installed the library you need to get a client ID and client secretof Spotify in order to use their API. Go to the Dashboard for Spotify developers and login with your Spotify account.

After you have login with your Spotify account you will see this dashboard:

Alt Text

Click on CREATE A CLIENT ID and follow the steps that are instructed on the page.

After you have created your app you will see the dashboard of your Spotify application.

Alt Text

You will see your Client ID and Client Secret which you will need to use the application. Quick note: Do not share your client secret with other people.

Lastly, you need to add a link that re-direct you to a page that you need to authenticate your Spotify app. On your Dashboard, click on EDIT SETTINGS and go to Redirect URIs. Enter your local Google link here (I live in the Netherlands so my url I use is https://www.google.nl/). Add your redirecting url and click on SAVE below.

Alt Text

Writing the code

For making the file where we write the Python code we use VSCODE as our Text editor. You are free to use another IDE or text editor if you want to.

Name your python file spotify-app.py and save it to a location you can find it.

Now for writing the code we need first to import the libraries needed for the script:

# Import libraries
import os
import sys
import json
import spotipy
import webbrowser
import spotipy.util as util
from json.decoder import JSONDecodeError

Next you need get your username in the terminal and the scope:

# Get the username from terminal
username = sys.argv[1]
scope = 'user-read-private user-read-playback-state user-modify-playback-state'

You need to use the scope in order to authorize the username and the webbrowser for SPOTIPY_REDIRECT_URI which will redirect you to your given URL.

Next you need to erase cache and ask the user for permission:

try:
    token = util.prompt_for_user_token(username, scope)
except (AttributeError, JSONDecodeError):
    os.remove(f".cache-{username}")
    token = util.prompt_for_user_token(username, scope)

This will open a web page that ask you for permission to use your Spotify account for the app every time you launch the script from the terminal. It will remove your old data if you launch again from the terminal.

Then create a Spotify object:

# Create Spotify object
spotifyObject = spotipy.Spotify(auth=token)

To play the song from Spotify it is handy to display from which device you're playing your song from:

devices = spotifyObject.devices()
print(json.dumps(devices, sort_keys=True, indent=4))
deviceID = devices['devices'][0]['id']

For getting the track information, you need a variable that uses the spotifyObject and arrays that list the information of the track, such as name of the track and artist name:

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

if artist !="":
    print("Currently playing " + artist + " - " + track)

Lastly, you want to display the user information as well. For this you have to make a variable that gets the info using the Spotify API and to display the user name of the user:

# User information
user = spotifyObject.current_user()
displayName = user['display_name']
follower = user['followers']['total']

Now we come at the most important part of our code. First, we are creating a while loop that prints the first thing you see when running the application and giving you options how to use the script:

while True:

    print()
    print(">>> Welcome to Spotify " + displayName + " :)")
    print(">>> You have " + str(follower) + " followers.")
    print()
    print("0 - Search for an artist")
    print("1 - exit")
    print()`
    choice = input("Enter your choice: ")

In this code you can see it welcome us displaying our username and give us to options to use the app: Search for an artist (pressing 0) or exit it (pressing 1).

If we choose "0" then we search for an artist using the if-statement:

# Search for artist
if choice == "0":
    print()
    searchQuery = input("Ok, what's their name?:")
    print()

Then we need to get the search results:

   # Get search results
   searchResults = spotifyObject.search(searchQuery,1,0,"artist")

For the search results it ask us four parameters:

  • the searchQuery - the prompt we ask to user to enter the artist name -
  • the limit - the number of items to return, we want only want 1 item
  • the offset - the index of the item to return, so the first one, thus 0
  • the type of item to return - we want it to return the artist name

Next, we want to print the artist details

    # Print artist details
    artist = searchResults['artists']['items'][0]
    print(artist['name'])
    print(str(artist['followers']['total']) + " followers")
    print(artist['genres'][0])
    print()
    webbrowser.open(artist['images'][0]['url'])
    artistID = artist['id']

We also want to have the album details:

    # Album details
    trackURIs = []
    trackArt = []
    z = 0

After this we want to extract the data from the album and then the data from the track:

    # Extract data from album
    albumResults = spotifyObject.artist_albums(artistID)
    albumResults = albumResults['items']

    for item in albumResults:
        print("ALBUM: " + item['name'])
        albumID = item['id']
        albumArt = item['images'][0]['url']

        # Extract track data
        trackResults = spotifyObject.album_tracks(albumID)
        trackResults = trackResults['items']

        for item in trackResults:
            print(str(z) + ": " + item['name'])
            trackURIs.append(item['uri'])
            trackArt.append(albumArt)
            z+=1
        print()

To extract the data we use a for loop where we loop the item in the album results and the item in the amount of album results. It will print a string that show the album names and the track names.

Then we want to display the album art:

    # See album art
    while True:
        songSelection = input("Enter a song number to see the album art: ")
        if songSelection == "x":
            break
        trackSelectionList = []
        trackSelectionList.append(trackURIs[int(songSelection)])
        spotifyObject.start_playback(deviceID, None, trackSelectionList)
        webbrowser.open(trackArt[int(songSelection)])

We use a while loop where we ask the user to enter the song number of the artist. If the user want to exit the program, then he/she should press "x" to exit the program.

We also made an empty list where we add the tracks. The start_playback uses three parameters:

  • device ID - the device where the song will play
  • context uri - spotify context for the URI, in this case it is None
  • uris - the spotify track uris, so in this case our empty list called trackSelectionList

Lastly, we want also to be able to exit our program:

# End program
if choice == "1":
    break

If you are interested in the full code, click here to see the full code.

Using the terminal to launch the script

Now open the terminal and change the directory to the location where you have saved your python file.

Before launching the python file you need to enter these commands with your Spotipy credentials:

If you're using Linux/MacOS, enter the following commands below:
export SPOTIPY_CLIENT_ID="Enter your client ID here"
export SPOTIPY_CLIENT_SECRET="Enter your client secret here"
export SPOTIPY_REDIRECT_URI="Enter your redirect URL here"

If you're using Windows, use the set command and remove the apostrophes:
set SPOTIPY_CLIENT_ID=Enter your client ID here
set SPOTIPY_CLIENT_SECRET=Enter your client secret here
set SPOTIPY_REDIRECT_URI=Enter your redirect URL here

Now enter the following command to launch the script:
python spotify-app.py "your-username"

It will show you an authentication page where it ask you for permission and will redirect you to the link you have given in the terminal to redirect.

Copy the url that is given in the web browser and paste it into terminal then press Enter.

You will see this information below:
Alt Text

Now let test the application.

First open the Spotify application on your device or in your browser.

Then press 0 in the terminal to continue our application.

It will display to ask us to enter the name of the artist. For example, let's say we want to display the album and tracks of the K-POP group 'BLACKPINK'.

Enter 'BLACKPINK' in the terminal and press enter (remember the script is case-sensitive, so make sure you enter the artist name correctly).

It will display the album art in the webbrowser:

Alt Text

And it will show us the album and tracks in the terminal:

Alt Text

Now if we want Spotify to play the song, we have to enter the number of the track name. For example, we want to play the song 'BOOMBAYAH', which is number 104. So enter this number in the terminal. It will show the album art in your browser and play the song in Spotify application.

That's it!

Credits

I was able to create this program thanks to this tutorial series by Ian Annase and the Spotipy library. Thanks to these resources I was able to create this program and write this tutorial.

If you have any questions/remarks, feel free to post them 😄

Quick note

This tutorial is part of the #31DaysOfCode challenge where I challenge myself to learn Python. I wrote several articles already about my progress and how I try to overcome obstacles and what I've learnt.

Posted on by:

helloiamarra profile

Arra

@helloiamarra

I am Arra. I am a software developer who works on a variety of range of disciplines as automation, testing, web development, and more.

Discussion

markdown guide
 

hi, could you please update the link for the full code? It doesn't work to me