Change OS X system volume programmatically

前端 未结 3 867
被撕碎了的回忆
被撕碎了的回忆 2020-12-19 13:09

How can I change the volume programmatically from Objective-C?

I found this question, Controlling OS X volume in Snow Leopard which suggests to do:

3条回答
  •  温柔的废话
    2020-12-19 13:51

    You need to get the default audio device first:

    #import 
    
    AudioObjectPropertyAddress getDefaultOutputDevicePropertyAddress = {
      kAudioHardwarePropertyDefaultOutputDevice,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
    };
    
    AudioDeviceID defaultOutputDeviceID;
    UInt32 volumedataSize = sizeof(defaultOutputDeviceID);
    OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                                 &getDefaultOutputDevicePropertyAddress,
                                                 0, NULL,
                                                 &volumedataSize, &defaultOutputDeviceID);
    
    if(kAudioHardwareNoError != result)
    {
      // ... handle error ...
    }
    

    You can then set your volume on channel 1 (left) and channel 2 (right). Note that channel 0 (master) does not seem to be supported (the set command returns 'who?')

    AudioObjectPropertyAddress volumePropertyAddress = {
      kAudioDevicePropertyVolumeScalar,
      kAudioDevicePropertyScopeOutput,
      1 /*LEFT_CHANNEL*/
    };
    
    Float32 volume;
    volumedataSize = sizeof(volume);
    
    result = AudioObjectSetPropertyData(defaultOutputDeviceID,
                                        &volumePropertyAddress,
                                        0, NULL,
                                        sizeof(volume), &volume);
    if (result != kAudioHardwareNoError) {
      // ... handle error ...
    }
    

    Hope this answers your question!

提交回复
热议问题