Friday, February 22, 2013

Make your media keys work with Spotify in Linux

This will be a quicky. I just wanted to document how I made my media keys work for Spotify in Linux. I’m going to give instructions for Ubuntu, but it shouldn’t be hard to adapt to any Linux distro.

First install xbindkeys:

apt-get install xbindkeys

Next put this in a file named .xbindkeysrc in your home directory (e.g. vim ~/.xbindkeysrc)

"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause" XF86AudioPlay
"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Stop" XF86AudioStop
"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Previous" XF86AudioPrev
"dbus-send --print-reply --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.Next" XF86AudioNext

To test open a command line and run

xbindkeys &

Finally make sure xbindkeys is started when you login by opening your “Startup Applications” settings and adding the xbindkeys command. You can do this from the command line by creating a the file ‘~/.config/autostart/xbindkeys.desktop with the following contents:

[Desktop Entry]
Type=Application
Exec=xbindkeys
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[en_US]=xbindkeys
Name=xbindkeys
Comment[en_US]=
Comment=

If it’s not working for you it’s probably because xbindkeys isn’t picking up the keys. To test this run: xbindkeys -k

Then press the pause/play button. If xbindkeys sits there and doesn’t recognize it then this is your problem. To fix this simply go to your keyboard shortcut preferences (System Settings -> Keyboard -> Shortcuts -> Sound and Media) and change the accelerators for “Play (or play/pause)”, “Stop playback”, “Previous track” and “Next track” to something different. I changed them to Ctrl+[pause/play button], Ctrl+[stop button], Ctrl+[previous] and Ctrl+[next] respectively. After you’ve done this it will allow xbindkeys to capture the shortcut. Keep in mind that if xbindkeys is already running in the background then xbindkeys -k will still not capture the keys but they will work.