Search code examples
swiftmacoseventsvolume

Capture system volume changes in Swift


Reading the following advices about getting and setting system volume in osX, I use the ISSoundAdditions which works great:

Change Volume on Mac programmatically

and

Set OS X volume in OS X 10.11 using Swift without using the deprecated AudioHardwareServiceSetPropertyData API

I can directly manage the system sound volume with a NSSlider (with bindings). My question is: how can I capture the volume changed as an event (for exemple when the volume up and down keys in the keyboard ? In theses cases, my slider doesn't react. I experimented :

self.addObserver(self, forKeyPath: "volume.systemVolume", options: NSKeyValueObservingOptions.New, context: &volumeContext)

But then I get an exception:

Cannot update for observer XX for the key path "volume.systemVolume", most likely because the value for the key "volume" has changed without an appropriate KVO notification being sent. Check the KVO-compliance of the class.

BTW, systemVolume property is a class property, if it matters?

Many thanks for your help

Joshua


Solution

  • I used (Swift 4):

    DistributedNotificationCenter.default.addObserver(self,
                                               selector: #selector(eventFunction(_:)),
                                               name: NSNotification.Name(rawValue: "com.apple.sound.settingsChangedNotification"),
                                               object: nil)
    

    Where the function is defined like:

    @objc func volumeChangeEvent(_ evt: NSEvent) { }