Handling media keys in GNOME with Python

, | Tweet this

Spent a while figuring out how to get Miro to handle media keys in Gnome. My current understanding (and this could be entirely wrong) is that as of 2.18, Gnome handles the multimedia keys. In order for your application to respond to multimedia keys, you have to connect to the signal through dbus.

My biggest problem is that my web searching revealed a lot of bugs, but no documentation. I did finally find Handling multimedia keys in GNOME 2.18 and then worked out the rest. I still have no clue where to find the documentation for it.

Here's what I got working:

import logging
import dbus

from miro import app

class MediaKeyHandler(object):
    def __init__(self, window):
        self.app = "Miro"
        self.bus = dbus.Bus(dbus.Bus.TYPE_SESSION)
        self.bus_object = self.bus.get_object(
            'org.gnome.SettingsDaemon', '/org/gnome/SettingsDaemon/MediaKeys')

            self.app, 0, dbus_interface='org.gnome.SettingsDaemon.MediaKeys')

            'MediaPlayerKeyPressed', self.handle_mediakey)

        window.connect("focus-in-event", self.on_window_focus)

    def handle_mediakey(self, application, *mmkeys):
        if application != self.app:
        for key in mmkeys:
            if key == "Play":
            elif key == "Stop":
            elif key == "Next":
            elif key == "Previous":

    def on_window_focus(self, window):
            self.app, 0, dbus_interface='org.gnome.SettingsDaemon.MediaKeys')
        return False

def get_media_key_handler(window):
    Creates and returns a MediaKeyHandler or returns None if such a thing
    is not available on this platform.

    :param window: a Gtk.Window instance
        return MediaKeyHandler(window)
    except dbus.DBusException:
        logging.exception("cannot load MediaKeyHandler")

If you see problems with this, let me know so I can ammend the code.

November 5th, 2010 - Fixed a bug in the code.
November 9th, 2010 - Tweaked the code to re-assert key handling on focus.

Want to comment? Send an email to willkg at bluesock dot org. Include the url for the blog entry in your comment so I have some context as to what you're talking about.