I mute and later unmute the OS X system volume with the following code:
void SetMute(AudioDeviceID device, BOOL mute)
{
UInt32 muteVal = (UInt32)mute;
AudioObjectPropertyAddress address = {
kAudioDevicePropertyMute,
kAudioDevicePropertyScopeOutput,
0
};
OSStatus err;
err = AudioObjectSetPropertyData(device,
&address,
0,
NULL,
sizeof(UInt32),
&muteVal);
if (err)
{
NSString * message;
/* big switch statement on err to set message */
NSLog(@"error while %@muting: %@", (mute ? @"" : @"un"), message);
}
}
The value of device
is determined with
AudioDeviceID GetDefaultAudioDevice()
{
OSStatus err;
AudioDeviceID device = 0;
UInt32 size = sizeof(AudioDeviceID);
AudioObjectPropertyAddress address = {
kAudioHar开发者_如何学CdwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
err = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&address,
0,
NULL,
&size,
&device);
if (err)
{
NSLog(@"could not get default audio output device");
}
return device;
}
And I also check whether the system volume is currently muted, with:
BOOL GetMute(AudioDeviceID device)
{
UInt32 size = sizeof(UInt32);
UInt32 muteVal;
AudioObjectPropertyAddress address = {
kAudioDevicePropertyMute,
kAudioDevicePropertyScopeOutput,
0
};
OSStatus err;
err = AudioObjectGetPropertyData(device,
&address,
0,
NULL,
&size,
&muteVal);
if (err)
{
NSString * message;
/* big switch to set message */
NSLog(@"error while getting mute status: %@", message);
}
return (BOOL)muteVal;
}
All of this seems to work fine -- the system mutes and unmutes with the same behavior as if the user hit the mute key on the keyboard (unmuting restores the last volume set before muting, etc).
I have noticed that at some unspecified time after my program does this, coreaudiod
begins to consume a lot more CPU than normal (in my case, this is only around 5-7%, but ordinarily it reports 0.0% in Activity Monitor). As far as I can tell, I'm using the Core Audio APIs correctly there, and nothing looks like it should be causing any glitches in coreaudiod
, so I'm hoping that someone can either point out an issue with my code, or point me towards what else (possibly unrelated?) might be causing the CPU usage in coreaudiod
. I should also note that when I observe coreaudiod
using more CPU than normal, there's no sound playing, and the system is unmuted.
精彩评论