Spotify is probably one of my favorite companies that leverage Data Science. As you can read from their website, “Speed is a big focus for Spotify. Python fits well into this mindset, as it gets us big wins in speed of development”. I was over at a friends last weekend and he has an Amazon Echo that allows you to stream music on voice command for $200. Thus the idea for this blog post. If I knew how to access my Spotify Premium account from Python, maybe I could have my own Echo with a $5 Raspberry Pi Zero?
Speed of development
“To-market speed” is key with the Python programming language. This blog post is a prime example. Yesterday I knew nothing about the Python package PySpotify, but about four hours later I was ready for today’s post.
Spotify Stream – The Objectives
For now we’re going to call it a success if we can login to our account, search for The Beatles’ Blackbird, and play Blackbird. First we use the login feature already available with the PySpotify package Spotify.Session(). Assuming that a file called spotify_appkey.key exists in the present folder (this is the binary you should have downloaded from Spotify), Spotify.Session() should take care of the heavy lifting.
We use the Threading module to make sure Python doesn’t step on itself while performing the actions. We also use event listeners to “listen” for a good connection and the end of the tracks we play. AlsaSink is used on Linux for Python to access the speakers on the computer. Logged_in.wait() is what we’ve been hoping for. If you see either of the print statements from the try/except portion of the above code, you have successfully logged into Spotify from Python.
How Do You Find an Artist?
We’re searching for The Beatles’ song Blackbird. In order to play the song, we need to know Spotify’s identification number for that track – they call it a URI. There are different formats for URIs depending on what you would like to do:
- there are more I’m sure
From our perspective, we want to search for spotify:artist then try to find spotify:track.
Now Go Get the Track
Now that we can search for any given artist, we now pass the resulting lists to another function that plays the track. One key to this process is the use of the Track(u’spotify:track:blahblahblah’) object. PySpotify allows you to load the track object directly into the session.player.load() method. Now we’re in business.
What Is Next?
In the near future we will review implementing our code on a Raspberry Pi and expanding with other needed functions as we go. Maybe we want to play a specific song when motion is detected or if a house doorbell is rung. The possibilities are endless!