In this article, we will cover how to play Spotify audio with Python.
Spotify is one of the world’s largest music streaming service providers. In this article we will access Spotify using Spotipy, It is a lightweight Python library for the Spotify Web API with Spotify one can get full access to all of the music data provided by the Spotify platform. One can also retrieve Spotify content such as album data, playlists, and even songs using the API. Here we will see how can we use Spotipy library for this purpose.
Required Packages
pip install spotipy
Setting up Spotify App
Step 1: Create an account or log in to your Spotify Developers account here.
Step 2: Create an App.
Step 3: The dashboard would be opened. Now, Save your Client Id, Client Secret, this will be used later in our program.
Step 4: Click on the “EDIT SETTING” button and add in the Redirect URIs as follow.
http://google.com/callback/
Step 5: Click on add and save the changes.
Stepwise Implementation
Step 1: Now follow the steps below to set up a virtual environment.
- Create a folder for this project.
- Go to the command prompt and set the path to the folder created.
- The below command is used to set up a virtual environment for our project to run.
python -m venv .env
- The below command is to activate the virtual environment.
.env\Scripts\activate
Step 2:
In this step, we will import Spotify. The web browser is imported so that after authentication we will be redirected to the specified URL via the browser. We import JSON to accept the response from the browser, which is in the JSON code format.
Python3
import json import spotipy import webbrowser |
Step 3:
In this step, we will add the required credentials Here in the place of Your_Client_Id and Your_Client_Secret credentials which you’ve noted in Step 3. Click here To know your username and replace it in place of Your_Username.
Python3
username = 'Your user name' clientID = 'your client ID' clientSecret = 'Your client secret' |
Step 4:
The following lines are used to validate our info and provide access to our Spotify account.
- oauth_object is an object that we create, to access the function SpotifyOAuth from our installed library Spotify. Here we pass the clientID, clientSecret, and redirect URI. This function now checks if the clientID, clientSecret, and redirect URI are valid or not.
- token_dict which gets the token as proof of our authorized access to Spotify.
- spotipy.Spotify(auth=token) this is the actual step where the token generated in the previous step gets authorized.
- user = spotifyObject.current_user(), this particular line gets all the details of the user and combines them.
- This user information is used to retrieve the JSON response sent by the browser to our system. The print statement here is used to print this JSON response.
Python3
oauth_object = spotipy.SpotifyOAuth(clientID, clientSecret, redirect_uri) token_dict = oauth_object.get_access_token() token = token_dict[ 'access_token' ] spotifyObject = spotipy.Spotify(auth = token) user_name = spotifyObject.current_user() # To print the response in readable format. print (json.dumps(user_name, sort_keys = True , indent = 4 )) |
Step 5:
In this step, we will create a user functionality loop.
- When 1 is given as input, the name of the song to be searched is typed, and it plays the desired song.
- When 0 is given as the input it exits the program.
Python3
while True : print ( "Welcome to the project, " + user_name[ 'display_name' ]) print ( "0 - Exit the console" ) print ( "1 - Search for a Song" ) user_input = int ( input ( "Enter Your Choice: " )) if user_input = = 1 : search_song = input ( "Enter the song name: " ) results = spotifyObject.search(search_song, 1 , 0 , "track" ) songs_dict = results[ 'tracks' ] song_items = songs_dict[ 'items' ] song = song_items[ 0 ][ 'external_urls' ][ 'spotify' ] webbrowser. open (song) print ( 'Song has opened in your browser.' ) elif user_input = = 0 : print ( "Good Bye, Have a great day!" ) break else : print ( "Please enter valid user-input." ) |
Step 6:
Create a python file and add the below code in the file (spotify.py).
Note: Make sure that the python file’s location and the virtual environment location are the same.
Python3
import json import spotipy import webbrowser username = 'Your user name' clientID = 'your client ID' clientSecret = 'Your client secret' oauth_object = spotipy.SpotifyOAuth(clientID, clientSecret, redirect_uri) token_dict = oauth_object.get_access_token() token = token_dict[ 'access_token' ] spotifyObject = spotipy.Spotify(auth = token) user_name = spotifyObject.current_user() # To print the JSON response from # browser in a readable format. # optional can be removed print (json.dumps(user_name, sort_keys = True , indent = 4 )) while True : print ( "Welcome to the project, " + user_name[ 'display_name' ]) print ( "0 - Exit the console" ) print ( "1 - Search for a Song" ) user_input = int ( input ( "Enter Your Choice: " )) if user_input = = 1 : search_song = input ( "Enter the song name: " ) results = spotifyObject.search(search_song, 1 , 0 , "track" ) songs_dict = results[ 'tracks' ] song_items = songs_dict[ 'items' ] song = song_items[ 0 ][ 'external_urls' ][ 'spotify' ] webbrowser. open (song) print ( 'Song has opened in your browser.' ) elif user_input = = 0 : print ( "Good Bye, Have a great day!" ) break else : print ( "Please enter valid user-input." ) |
Step 7:
Execute your program in the command prompt using the following command.
python spotify.py
Execution of the program
Step 1: After the first execution of the program, you’ll be redirected to the following page. Agree to the conditions to proceed further.
Step 2: After agreeing, It will be redirected to a google page. Just Copy the page’s URL and paste it into the command prompt and click enter.
Step 3: You’ll see such JSON code appearing on your command prompt screen.
Step 4: Now run your python file again in the command prompt using the command python spotify.py. It will ask for user input.
- Press 0 to exit.
- Press 1 to enter the song name to be played.