0

Using AudioUnit and kAudioUnitSubType_HALOutput how do I detect if the output is Speaker or Headset?

junglecat
  • 643
  • 1
  • 10
  • 19

1 Answers1

2
bool usingInternalSpeakers()
{
    AudioDeviceID defaultDevice = 0;
    UInt32 defaultSize = sizeof(AudioDeviceID);

    const AudioObjectPropertyAddress defaultAddr = {
        kAudioHardwarePropertyDefaultOutputDevice,
        kAudioObjectPropertyScopeGlobal,
        kAudioObjectPropertyElementMaster
    };

    AudioObjectGetPropertyData(kAudioObjectSystemObject, &defaultAddr, 0, NULL, &defaultSize, &defaultDevice);

    AudioObjectPropertyAddress property;
    property.mSelector = kAudioDevicePropertyDataSource;
    property.mScope = kAudioDevicePropertyScopeOutput;
    property.mElement = kAudioObjectPropertyElementMaster;

    UInt32 data;
    UInt32 size = sizeof(UInt32);
    AudioObjectGetPropertyData(defaultDevice, &property, 0, NULL, &size, &data);

    return data == 'ispk';
}


int main(int argc, const char * argv[])
{


    if (usingInternalSpeakers())
        printf("I'm using the speakers!");
    else
        printf("i'm using the headphones!");
    return 0;
}
shaish
  • 1,479
  • 1
  • 12
  • 23
  • 2
    Is there any way to be notified of a change? For example we can listen for AVAudioSessionRouteChangeNotification in iOS. – bugloaf Apr 30 '18 at 14:12