hi-everyone hi-everyone - 7 months ago 26
Swift Question

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

I found this code to set the system volume using Swift. While using the code in a playground I got warning.


AudioHardwareServiceSetPropertyData was deprecated in OS X 10.11


How do I update the code for OS X 10.11?

Thanks.
:)

mz2 mz2
Answer

As also suggested in this answer to a similar Objective-C question, I'd suggest using ISSoundAdditions, which you can call from Swift as such:

NSSound.setSystemVolume(0.5)

The implementation of -setSystemVolume begins around line 113 in ISSoundAdditions.m in case you're curious of how they accomplish setting the system volume.

To clarify a factually challenged comment to my answer (since deleted, apparently), there is no use of deprecated APIs in ISSoundAdditions when compiling with the El Capitan SDK – AudioHardwareServiceSetPropertyData is not used. AudioObjectSetPropertyData is indeed the API one should switch to if using the deprecated AudioHardwareServiceSetPropertyData, though as you can see from the ISSoundAdditions implementation I linked to, there's a bit of work involved (hence I linked to the implementation in the first place).