Is there a way to emulate key presses of the media keys (volume up/down, play, pause, prev, next) on common Apple notebooks?
How?
On your Mac, choose Apple menu > System Preferences, click Keyboard , then click Keyboard. Click Modifier Keys. For each modifier whose default action you want to change, click the pop-up menu, then choose the action you want performed when you press the key, or choose No Action.
The Mac Media Key Forwarder utility makes the media keys actually useful instead of an erratic mess. It allows you to prioritise Spotify or Apple Music, despite whatever else is going on in the OS.
That took some time and many hacks (trying around with ctypes, the IOKit native interface, Quartz and/or Cocoa). This seems like an easy solution now:
#!/usr/bin/python
import Quartz
# NSEvent.h
NSSystemDefined = 14
# hidsystem/ev_keymap.h
NX_KEYTYPE_SOUND_UP = 0
NX_KEYTYPE_SOUND_DOWN = 1
NX_KEYTYPE_PLAY = 16
NX_KEYTYPE_NEXT = 17
NX_KEYTYPE_PREVIOUS = 18
NX_KEYTYPE_FAST = 19
NX_KEYTYPE_REWIND = 20
def HIDPostAuxKey(key):
def doKey(down):
ev = Quartz.NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
NSSystemDefined, # type
(0,0), # location
0xa00 if down else 0xb00, # flags
0, # timestamp
0, # window
0, # ctx
8, # subtype
(key << 16) | ((0xa if down else 0xb) << 8), # data1
-1 # data2
)
cev = ev.CGEvent()
Quartz.CGEventPost(0, cev)
doKey(True)
doKey(False)
for _ in range(10):
HIDPostAuxKey(NX_KEYTYPE_SOUND_UP)
HIDPostAuxKey(NX_KEYTYPE_PLAY)
(While I needed this in Python for now, my question was not really Python related and of course you can easily translate that to any other language, esp. ObjC.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With