Search code examples
swiftmacosnsnotificationcenteravaudioengine

Observing System Volume Changes OSX - Swift


I'm trying to execute a method when the system volume changes.

I've tried using DistributedNotificationCenter.default().addObserver(self,selector: #selector(volumeChanged(_:)),name: NSNotification.Name(rawValue: "com.apple.sound.settingsChangedNotification"),object: nil) but it didn't work.

Well, it does work. But only if the System Preferences app is open.

What's the right way to accomplish this task?

Ps: note that it's on MacOS, not iOS


Solution

  • After trying countless ways I found a nice workaround: instead of searching for a probably non-existent notification, I try to get the physical key-press event. As the media keys are not sending a normal CGEvent I came up with this solution: Capture OSX media control buttons in Swift

    Note that the TouchBar simulates such a key event, so any app that you'll write using this method will also work for those MacBook models which have the TouchBar.

    It's probably not the ideal solution, but it works. If anyone knows a better way please let me know.