gpt4 book ai didi

objective-c - 如何获取计算机当前的音量级别?

转载 作者:太空狗 更新时间:2023-10-30 03:48:39 24 4
gpt4 key购买 nike

如何从 Cocoa API 访问 Mac 的当前音量级别?

例如:当我在 OS X 10.7 上使用 Spotify.app 时出现声音广告,而我调低 Mac 的音量时,该应用程序会暂停广告,直到我将其调回平均水平。我发现这非常令人讨厌并且侵犯了用户隐私,但不知何故 Spotify 找到了一种方法来做到这一点。

有什么方法可以用 Cocoa 做到这一点吗?我正在制作一个应用程序,如果音量低,它可能会有用地警告用户。

最佳答案

有两个选项可用。第一步是确定您想要的设备并获取其 ID。假设默认输出设备,代码将类似于:

AudioObjectPropertyAddress propertyAddress = { 
kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};

AudioDeviceID deviceID;
UInt32 dataSize = sizeof(deviceID);
OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize, &deviceID);

if(kAudioHardwareNoError != result)
// Handle the error

接下来,您可以使用 kAudioHardwareServiceDeviceProperty_VirtualMasterVolume获取设备的虚拟主卷的属性:

AudioObjectPropertyAddress propertyAddress = { 
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume,
kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster
};

if(!AudioHardwareServiceHasProperty(deviceID, &propertyAddress))
// An error occurred

Float32 volume;
UInt32 dataSize = sizeof(volume);
OSStatus result = AudioHardwareServiceGetPropertyData(deviceID, &propertyAddress, 0, NULL, &dataSize, &volume);

if(kAudioHardwareNoError != result)
// An error occurred

或者,您可以使用 kAudioDevicePropertyVolumeScalar 获取特定 channel 的音量:

UInt32 channel = 1; // Channel 0  is master, if available
AudioObjectPropertyAddress propertyAddress = {
kAudioDevicePropertyVolumeScalar,
kAudioDevicePropertyScopeOutput,
channel
};

if(!AudioObjectHasProperty(deviceID, &propertyAddress))
// An error occurred

Float32 volume;
UInt32 dataSize = sizeof(volume);
OSStatus result = AudioObjectGetPropertyData(deviceID, &propertyAddress, 0, NULL, &dataSize, &volume);

if(kAudioHardwareNoError != result)
// An error occurred

两者之间的区别在Apple's docs中解释。 :

kAudioHardwareServiceDeviceProperty_VirtualMasterVolume

A Float32 value that represents the value of the volume control. The range for this property’s value is 0.0 (silence) through 1.0 (full level). The effect of this property depends on the hardware device associated with the HAL audio object. If the device has a master volume control, this property controls it. If the device has individual channel volume controls, this property applies to those identified by the device's preferred multichannel layout, or the preferred stereo pair if the device is stereo only. This control maintains relative balance between the channels it affects.

因此,准确定义设备的音量可能很棘手,尤其是对于具有非标准 channel 映射的多 channel 设备。

关于objective-c - 如何获取计算机当前的音量级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8950727/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com