[macOS Developer Tip] Audio that respects macOS’ “Play user interface sound effects” setting

In System Preferences > Sound > Sound Effects, users have the choice to turn off user interface sound effects (as an example, that might be a “tick” sound when adjusting a slider, or a “lock/unlock” sound when clicking a Lock button).

But how do you respect that setting? NSSound surely doesn’t.
Well, I found two ways to do it:

The “Easy” Way

macOS has a key in the standard UserDefaults object

com.apple.sound.uiaudio.enabled

If it is present and set to true, it’s safe to play the ui sound.

The “Safe” Way

What if the UserDefaults key isn’t present? Or you just want to be absolutely certain that your sound respects the user’s setting?

Use the AudioToolbox APIs. It offers

AudioServicesSetProperty(kAudioServicesPropertyIsUISound,...)

which marks sounds as UI sounds, thus not playing if the user wishes them not to.

It’s a bit more work, but might be the safer way to do it.