Tell last media player to skip song I bought a new keyboard that, of course, works almost perfectly, minus the media buttons. Luckily it has open source drivers specifically for linux and mac, but unfortunately the media buttons (specifically the next/previous) do not work.

I have the ability to run a command when they are pressed; I was hoping to recreate the Apple Keyboard next/previous functionality where it skips the song of the most recent media player.

I've found several scripts that will skip iTunes or Spotify individually, but I have music in both that I like to listen to.

How would I tell the last played media player next track?
Unfortunately Applescript does not offer a way to get a list of applications ordered by when they were last used - like when you press CMD-Tab.

Fortunately, somebody found a bit of Objective-C code that does get that information. I've wrapped it up and created this little command link tool that prints all the applications in order.

Now it is easy, a matter of calling it like this...

set zorder to (do shell script "/some/path/applist")

It produces a list of the applications' PID and their bundle identifier...

78540 com.apple.Terminal
68976 com.apple.ScriptEditor2
89228 org.mozilla.firefox
80897 com.barebones.textwrangler
1627 com.apple.finder
84894 com.azureus.vuze
54490 com.transtex.texeditplus
55055 com.apple.Dictionary
54549 com.apple.QuickTimePlayerX


The list should be just the apps visible when you press CMD-Tab and in the order displayed.

The rest should now be straight forward....

PS: This code compiled and run correctly on Snow Leopard (10.6), I don't know how/if it will run on newer versions...