I'm converting the Swift code for emulating media keys from another answer. Here's a stripped down version:
import Quartz
func doKey(down: Bool) {
let volumeDown = 1
let flags = NSEvent.ModifierFlags(rawValue: (down ? 0xa00 : 0xb00))
let data1 = Int((volumeDown << 16) | (down ? 0xa00 : 0xb00))
let ev = NSEvent.otherEvent(
with: NSEvent.EventType.systemDefined,
location: NSPoint(x: 0, y: 0),
modifierFlags: flags,
timestamp: 0,
windowNumber: 0,
context: nil,
subtype: 8,
data1: data1,
data2: -1
)
let cev = ev?.cgEvent
cev?.post(tap: CGEventTapLocation.cgSessionEventTap)
}
doKey(down: true)
doKey(down: false)
This works perfectly while saved as a script and run with swift ./script-name.swift
, but once I compile it (with or without notarisation) it no longer does what it's supposed to. There's no error in the terminal, just blank output and an exit code of zero.
Due to the nature of the code I thought it might be related to accessibility access. The first time I ran the compiled code, macOS asked for accessibility access for the Terminal but the tool still doesn't work. Also tried adding the tool itself manually in the System Preferences.
This is the only time I've encountered this problem. I feel I might be missing something basic.
Please don't suggest other ways to lower the volume. The goal is to understand and fix the underlying issue.