3

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. :)

Community
  • 1
  • 1

2 Answers2

8

I cannot yet comment, hence I post this as a separate answer. I have updated the great ISSoundAdditions to true Swift 5 and gave it a nice public interface, through which you manage the system volume by getting and setting a class property of NSSound– examples:

NSSound.systemVolume += 0.2
NSSound.systemVolumeIsMuted = true

As a little goodie, you can mute the system volume fading out smoothly (and non-blocking in the background):

NSSound.systemVolumeFadeToMute(seconds: 5.0, blocking: false)

Check it out: GitHub NSSound_SystemVolumeExtension

mabi99
  • 189
  • 1
  • 5
6

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).

Community
  • 1
  • 1
mz2
  • 4,672
  • 1
  • 27
  • 47
  • Thank you for your reply. When I replace ´AudioHardwareServiceSetPropertyData´ with ´AudioObjectSetPropertyData´ also my code is working, but because the Addition you recommended is much easier to use, I'll think over implementing the Addition. Thanks. :) –  Apr 30 '16 at 13:04