Open In App

How to play a Spotify audio with Python?

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.

python -m venv .env
.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.




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.




username = 'Your user name'
clientID = 'your client ID'
clientSecret = 'Your client secret'
redirect_uri = 'http://google.com/callback/'

Step 4:

The following lines are used to validate our info and provide access to our Spotify account.




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.




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.




import json
import spotipy
import webbrowser
  
username = 'Your user name'
clientID = 'your client ID'
clientSecret = 'Your client secret'
redirect_uri = 'http://google.com/callback/'
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.

 

 

 


Article Tags :