Skip to content

Instantly share code, notes, and snippets.

@drslump
Created June 4, 2012 19:13
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save drslump/2870240 to your computer and use it in GitHub Desktop.
Save drslump/2870240 to your computer and use it in GitHub Desktop.
Act upon media keys in a Mac under OSX
#!/usr/bin/python
import subprocess
# PyObjC-related imports
from AppKit import NSApplication, NSSystemDefined
from PyObjCTools import AppHelper
KEY_UP = 11
class KeySocketApp(NSApplication):
repeated = False
def sendEvent_(self, event):
if event.type() is NSSystemDefined and event.subtype() is 8:
data = event.data1()
keyCode = (data & 0xFFFF0000) >> 16
keyFlags = (data & 0x0000FFFF)
keyState = (keyFlags & 0xFF00) >> 8
keyRepeat = keyFlags & 0x1
if keyRepeat and keyState is not KEY_UP:
if keyCode == 20:
self.repeated = True
print "prev"
subprocess.call(['cmus-remote', '-k', '-10'])
elif keyCode == 19:
self.repeated = True
print "forward"
subprocess.call(['cmus-remote', '-k', '+10'])
if keyState is KEY_UP:
if self.repeated:
self.repeated = False
elif keyCode == 20:
print "PREV"
subprocess.call(['cmus-remote', '-r'])
elif keyCode == 16:
print "PLAY"
subprocess.call(['cmus-remote', '-u'])
elif keyCode == 19:
print "FORWARD"
subprocess.call(['cmus-remote', '-n'])
if __name__ == '__main__':
app = KeySocketApp.sharedApplication()
AppHelper.runEventLoop()
@drslump
Copy link
Author

drslump commented Jun 4, 2012

@00dani
Copy link

00dani commented Jun 17, 2013

I've been looking for a way to make my MacBook's media keys not worthless. This is perfect! Thanks. ^_^

@g5pw
Copy link

g5pw commented Jun 17, 2014

You can add the line

app.setActivationPolicy_(NSApplicationActivationPolicyProhibited)

just before line 51 and import NSApplicationActivationPolicyProhibited from AppKit to get rid of that useless dock icon! Credit to Albert on StackOverflow.

@adamv
Copy link

adamv commented Mar 30, 2016

All of the uses of is and is not in this script should be == and !=; is tests for object identity which happens to work for small integer values which are pre-created and reused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment