Using AudioToolbox from Swift to access the bulk of OS X

Is there a solution to set master system volume from my Swift app?

I have read a lot about AudioToolbox and read some source code examples in Objective-C. For example, I found this: Adjusting Mac OS X Volume After 10.6

But I cannot get it to work in Swift.

I am missing the code example at https://developer.apple.com/library/mac/documentation/AudioToolbox/Reference/AudioHardwareServicesReference/index.html#//apple_ref/c/func/AudioHardwareServiceGetPropertyData

+6


source to share


1 answer


(Code updated for Swift 4 and later, Swift 2 and 3 versions can be found in the edit history.)

Here's what I got by translating the answers to the system volume "Change OS X" programmatically and programmatically setting the Mac OS X volume after 10.6 (Snow Leopard) to "Swift" (brevity check not included):

Mandatory framework:

import AudioToolbox

      

Get default output device:

var defaultOutputDeviceID = AudioDeviceID(0)
var defaultOutputDeviceIDSize = UInt32(MemoryLayout.size(ofValue: defaultOutputDeviceID))

var getDefaultOutputDevicePropertyAddress = AudioObjectPropertyAddress(
    mSelector: kAudioHardwarePropertyDefaultOutputDevice,
    mScope: kAudioObjectPropertyScopeGlobal,
    mElement: AudioObjectPropertyElement(kAudioObjectPropertyElementMaster))

let status1 = AudioObjectGetPropertyData(
    AudioObjectID(kAudioObjectSystemObject),
    &getDefaultOutputDevicePropertyAddress,
    0,
    nil,
    &defaultOutputDeviceIDSize,
    &defaultOutputDeviceID)

      



Set volume:

var volume = Float32(0.50) // 0.0 ... 1.0
var volumeSize = UInt32(MemoryLayout.size(ofValue: volume))

var volumePropertyAddress = AudioObjectPropertyAddress(
    mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
    mScope: kAudioDevicePropertyScopeOutput,
    mElement: kAudioObjectPropertyElementMaster)

let status2 = AudioObjectSetPropertyData(
    defaultOutputDeviceID,
    &volumePropertyAddress,
    0,
    nil,
    volumeSize,
    &volume)

      

Finally, for the sake of completeness, we get the volume:

var volume = Float32(0.0)
var volumeSize = UInt32(MemoryLayout.size(ofValue: volume))

var volumePropertyAddress = AudioObjectPropertyAddress(
    mSelector: kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
    mScope: kAudioDevicePropertyScopeOutput,
    mElement: kAudioObjectPropertyElementMaster)

let status3 = AudioObjectGetPropertyData(
    defaultOutputDeviceID,
    &volumePropertyAddress,
    0,
    nil,
    &volumeSize,
    &volume)

print(volume)

      

Error checking has been omitted for brevity. Of course, in a real application, you should check the status return values ​​for success or failure.

Credits go to OS X volume setup on OS X 10.11 using Swift without using the deprecated AudioHardwareServiceSetPropertyData API to use AudioObjectSetPropertyData()

instead of the deprecated one AudioHardwareServiceSetPropertyData()

.

+13


source







All Articles