til/AppleScript: Spotify now playing
AppleScript is a scripting language created in 1993 by, you guessed it, Apple. It can be used to automate control of Mac applications that support it. This post is the start of a series where I'll show you how we can display information about the music you're playing on the desktop in macOS. We'll start by finding out what's playing in Spotify and getting some basic knowledge about AppleScript.
This is Script Editor. It comes with every Mac and we'll use it to write our scripts. First, we need to add Spotify to Script Editor to see what information we have access to. Open “Library” using Window → Library (or by pressing
shift + cmd + L). Click the
+ icon in the top (marked with a red circle in the image) and add Spotify from the applications' folder. If we double-click Spotify in the Library list, we'll see the information window in the middle with everything that is available to us.
Now we're ready to dive in to the code. We'll start by getting the artist's name and the name of the current track and print it like
<artist> - <track>.
tell application "Spotify" set artistName to artist of current track set trackName to name of current track set albumName to album of current track return artistName & " - " & trackName & " (" & albumName & ")" end tell
The syntax of AppleScript is pretty straight-forward. It's reminiscent of reading a text. Let's go through it line by line.
tell application "Spotify"– A
tellblock directs all commands inside it to the target specified after the
application “Spotify”in our case. This puts us in the Spotify context and it's only inside one of these blocks that we have access to all the information we found earlier.
set artistName to artist of current track– This creates a variable,
artistName, with the artist of the current track. In the library window, we can see that
current trackis available on the application level, that it returns a
trackand that a
artist. Something comparable in JS would be
const artistName = currentTrack.artist.
set trackName to name of current track– Same as above, but for the track name.
set albumName to album of current track– Same as above, but for the album name.
return artistName & " - " & trackName- This returns a string with our output, where the ampersands,
&, are AppleScript's way of doing string concatenation.
The output will be something like:
"Bring Me The Horizon - Can You Feel My Heart (Sempiternal)".
To run our code, we can click the play icon (▶️) at the top of the script window or press
cmd + R. The result will be displayed in a split window below our code. Currently, it will display the song information no matter what play state (
stopped) Spotify is in. We'll improve this in a coming post.
- AppleScript: Spotify now playing
- AppleScript: Spotify current position and track duration