Monday, June 29, 2009

Invoking Spotify playlist using applescript

Spotify has plenty of Finnish children's music available so it has gained specific popularity in our household. This has rendered my older iTunes-control -scripts not that useful anymore. I decided to give Spotify scripting a go, even though I knew there's not applescript interface available. Thankfully simple key navigation is enough for the basic use case of "play random song from this playlist":

-- Invoke Spotify simply by opening a Spotify playlist or artist URL

open location "http://open.spotify.com/artist/4Zml6rzsSiVkfIIWJh6EWX"

-- Make sure we have the spotify-application on front and in focus
tell application "Spotify"
activate
end tell

-- Now navigate to the song we want to play and play it
tell application "System Events"
-- Three times tabulator = move selection to the songs list
key code 48
key code 48
key code 48
-- Wait for a while the spotify app to catch up
delay (2)
-- enter key = play selected song
key code 36
-- right key with command = next song (random assumed)
key code 124 using command down
end tell
Note that if the Spotify URL is your private playlist this still works, as the playlist is invoked locally!

Other assumptions:
  • "enable access to assistive devices" is enabled on the "Universal Access" -settings
  • Spotify URL:s properly associated to your favourite browser (tested only with firefox)
Known issues:
  • Invoking a random song requires you to set the shuffle on manually on the Spotify app
  • Naturally this generates new browser tabs on each time the script is invoked
  • As the key events are used, and even with a noticeable wait in between, this can cause really weird results if something is happening onscreen either interactively or autonomously.
  • There is no straightforward way of knowing if Spotify is already playing something. Toggling the playback off, if invoked second time (useful when used with RFID tags) isn't therefore easy.. or is there a apparent solution other than closing the app?
As this works OK, I have to print out new RFID-tag for Ti-Ti -nalle for my daughters ;)

Again, the script is not really a rocket science and most of the elements were just copy&pasted from invaluable Doug's AppleScripts. It is just fun to simply being able to control other apps in OSX!