微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何从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,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,&volume);

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

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

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

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

Float32 volume;
UInt32 dataSize = sizeof(volume);
Osstatus result = AudioObjectGetPropertyData(deviceid,&volume);

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

Apple的文档解释了两者之间的区别:

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.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐