In your addGlobalMonitorForEventsMatchingMask
handler, save the current volume level and turn the volume down on both channels. You can do you own event processing in the handler before or after turning down the volume.
Before returning from the handler, restore the original volume, but include a delay to give the OS time to process the event (it will send the "funk," but you won't hear it).
One side effect: if you're listening to something (e.g., music), that will be briefly silenced, too.
My event code:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskKeyDown
handler:^(NSEvent *event) {
if ( event.type == NSEventTypeKeyDown ) {
if ( event.keyCode == 106 ) { // F16
// process the event here
[self adjustVolume:@(NO)];
[self performSelector:@selector(adjustVolume:) withObject:@(YES) afterDelay:0.3];
// 0.2 seconds was too soon
}
}
}];
My volume adjustment code:
- (void)adjustVolume:(NSNumber *)offOn
{
// get audio device...
AudioObjectPropertyAddress getDefaultOutputDevicePropertyAddress = {
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioDeviceID defaultOutputDeviceID;
UInt32 infoSize = sizeof(defaultOutputDeviceID);
AudioObjectGetPropertyData(kAudioObjectSystemObject,
&getDefaultOutputDevicePropertyAddress,
0, NULL,
&infoSize, &defaultOutputDeviceID);
// structurs to access the left/right volume setting
AudioObjectPropertyAddress volumePropertyAddress1 = {
kAudioDevicePropertyVolumeScalar,
kAudioDevicePropertyScopeOutput,
1 /* left */
};
AudioObjectPropertyAddress volumePropertyAddress2 = {
kAudioDevicePropertyVolumeScalar,
kAudioDevicePropertyScopeOutput,
2 /* right */
};
// save the original volume (assumes left/right are the same
static Float32 volumeOriginal; // could be an iVar
if ( offOn.boolValue == NO ) { // turn off
UInt32 volumedataSize = sizeof(volumeOriginal);
AudioObjectGetPropertyData(defaultOutputDeviceID,
&volumePropertyAddress1,
0, NULL,
&volumedataSize, &volumeOriginal);
//NSLog(@"volumeOriginal %f",volumeOriginal);
// turn off both channels
Float32 volume = 0.0;
AudioObjectSetPropertyData(defaultOutputDeviceID,
&volumePropertyAddress1,
0, NULL,
sizeof(volume), &volume);
AudioObjectSetPropertyData(defaultOutputDeviceID,
&volumePropertyAddress2,
0, NULL,
sizeof(volume), &volume);
} else { // restore
//NSLog(@"restoring volume");
AudioObjectSetPropertyData(defaultOutputDeviceID,
&volumePropertyAddress1,
0, NULL,
sizeof(volumeOriginal), &volumeOriginal);
AudioObjectSetPropertyData(defaultOutputDeviceID,
&volumePropertyAddress2,
0, NULL,
sizeof(volumeOriginal), &volumeOriginal);
}
}
With recognition to Thomas O'Dell for getting me started on this Change OS X system volume programmatically