Monday, May 04, 2009

Controlling Spotify

I love Spotify, but unfortunately it doesn't include an AppleScript dictionary. This is a little limiting when it comes to controlling it, but Mac OS X has a useful work around: GUI scripting.

With GUI scripting, you can use the "System Events" application to effectively click any item on the screen, including those of non-AppleScript applications. Using this principle, I modified my iTunes global Play/Pause script as follows to also control Spotify:

tell application "System Events"
 -- Check whether iTunes or Spotify is running
 set iTunes_instances to count (every process whose name is "iTunes")
 set Spotify_instances to count (every process whose name is "Spotify")
end tell

if iTunes_instances > 0 then
 -- iTunes support AppleScript, so is easy to control:
 tell application "iTunes" to playpause
else if Spotify_instances > 0 then
 -- Spotify doesn't. We want to keep it in the background, so check which app's active.
 set ActiveApp to (path to frontmost application as Unicode text)
 -- Bring Spotify forward so we can control it.
 tell application "Spotify" to activate
 
 -- Activate its "Play/Pause" control
 tell application "System Events"
  tell process "Spotify"
   click menu item 1 of menu "Playback" of menu bar 1
  end tell
 end tell
 
 -- Restore the previously-active app to the front
 tell application ActiveApp to activate
end if

So there you have it: a way to control Spotify without having to touch the mouse. Things will flash momentarily on the screen, but this shouldn't be too disruptive as you're telling the script to run anyway. I use QuickSilver to run this script whenever I hit F8. Very useful for working.

3 comments:

NeonPaul said...

That's pretty cool. Do you happen to know if there's anything that comes close to AppleScript on Windows?

Smiler said...

Re: NeonPaul
There's the Windows Scripting Host, which supports VBScript and (I think) JavaScript for running batch processing jobs and controlling applications. I'm not sure how versatile it really is though, nor how many applications support it. There might be some macro-recording utilities available that can do similar things though.

Just give it a google - something might turn up =).

Nasrin Akhther said...

clipping path | clipping path service in Usa | clipping path service | remove image background | Ghost Mannequin Service