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.

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

相关文章

我正在用TitaniumDeveloper编写一个应用程序,它允许我使用Ja...
我的问题是当我尝试从UIWebView中调用我的AngularJS应用程序...
我想获取在我的Mac上运行的所有前台应用程序的应用程序图标....
我是一名PHP开发人员,我使用MVC模式和面向对象的代码.我真的...
OSX中的SetTimer在Windows中是否有任何等效功能?我正在使用...
我不确定引擎盖下到底发生了什么,但这是我的设置,示例代码和...