Spotipy headless device user authentication from a separate device

54 views Asked by At

I'm trying to setup the Python Spotify API (spotipy) to run through a Python file in Ubuntu (Raspberry Pi) that should open Spotify and play a song. This works well when already logged in but I am having some problems with user authorisation on a headless device.

The code is supposed to run only with voice (voice recognition and speech generation) and no graphical interface. This makes it difficult to authorise the user details as shouting out their password is not a very secure way of doing it. This is a programme that will be running on an interactive voice assistant. This is my current code:

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy.oauth2 import SpotifyOAuth
import pyttsx3
import speech_recognition as sr

engine = pyttsx3.init()

# Create a recognizer object
recognizer = sr.Recognizer()
with sr.Microphone() as source:
   recognizer.adjust_for_ambient_noise(source)

# Spotify authentication
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="aaa000",
                                            client_secret="bbb111",
                                            redirect_uri="http://127.0.0.1:9090",
                                            scope = "user-library-read,user-read-playback-state,user-modify-playback-state"))

# Function for detecting speech
def listen():
   with sr.Microphone() as source:
       audio = recognizer.listen(source)
       try:
           sentence = recognizer.recognize_google(audio)
       except sr.UnknownValueError:
           speak("I didn't understand that, try again")    
           sentence = listen()
       except sr.RequestError:
           speak("I didn't understand that, try again")
           sentence = listen()
       return sentence

def play_song(song_name):
   results = sp.search(q = song_name, limit=1)
   for idx, track in enumerate(results['tracks']['items']):
       song_id = track['id']
   sp.start_playback(uris=["spotify:track:" + song_id])

if __name__ == "__main__":
   engine.say("What song do you want to play?")
   engine.runAndWait()
   song_name = listen()
   if song_name is not None:
       play_song(song_name)

I'm thinking of something like sending the redirected URL to another device, maybe through a server, which allows to login and authorise. I can't figure out how to do this, so I'd like to know if there is any way of authorising that would be easier, or if this is the only way.

0

There are 0 answers