Currently, I have code that successfully returns the value of the users system audio value that they can set with the volume keys.
However, what I want is a value of the audio the speakers are playing. So if the user is watching Netflix and a character starts screaming, the value would return higher than if the character was whispering.
Code I have now:
+ (AudioDeviceID)defaultOutputDeviceID {
OSStatus status = noErr;
AudioDeviceID outputDeviceID = kAudioObjectUnknown;
AudioObjectPropertyAddress propertyAOPA;
propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
propertyAOPA.mScope = kAudioObjectPropertyScopeGlobal;
propertyAOPA.mSelector = kAudioHardwarePropertyDefaultSystemOutputDevice;
UInt32 propertySize = sizeof(outputDeviceID);
if (!AudioHardwareServiceHasProperty(kAudioObjectSystemObject, &propertyAOPA)) {
NSLog(@"Cannot find default output device!");
return outputDeviceID;
}
status = AudioHardwareServiceGetPropertyData(kAudioObjectSystemObject, &propertyAOPA, 0, NULL, &propertySize, &outputDeviceID);
if(status) {
NSLog(@"Cannot find default output device!");
}
return outputDeviceID;
}
+ (float)volume {
OSStatus status = noErr;
AudioDeviceID outputDeviceID = [[self class] defaultOutputDeviceID];
if (outputDeviceID == kAudioObjectUnknown) {
NSLog(@"Unknown device");
return 0.0;
}
AudioObjectPropertyAddress propertyAOPA;
propertyAOPA.mElement = kAudioObjectPropertyElementMaster;
propertyAOPA.mScope = kAudioDevicePropertyScopeOutput;
propertyAOPA.mSelector = kAudioHardwareServiceDeviceProperty_VirtualMasterVolume;
Float32 outputVolume;
UInt32 propertySize = sizeof(outputVolume);
if (!AudioHardwareServiceHasProperty(outputDeviceID, &propertyAOPA)) {
NSLog(@"No volume returned for device 0x%0x", outputDeviceID);
return 0.0;
}
status = AudioHardwareServiceGetPropertyData(outputDeviceID, &propertyAOPA, 0, NULL, &propertySize, &outputVolume);
if (status) {
NSLog(@"No volume returned for device 0x%0x", outputDeviceID);
return 0.0;
}
if (outputVolume < 0.0 || outputVolume > 1.0)
return 0.0;
return outputVolume;
}