Question

I am using SpeakHere example code provided by Apple in my project.

How can I enable speakers If earphones or headphones are not plugged in?

I know I can overwrite the route using the following code..

OSStatus error;
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker; 
error = AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
if (error) printf("couldn't set audio speaker!");

But I don't want that because if earphones are plugged in, the sound should be coming out of them..

Was it helpful?

Solution

Most likely this is what you are looking for:

    UInt32 overrideValue = 1;
    AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(overrideValue), &overrideValue);

From the docs: Specifies whether or not to route audio to the speaker (instead of to the receiver) when no other audio route, such as a headset, is connected.

OTHER TIPS

here is a headphone/accessory detect method stolen/borrowed from here Detect if headphones (not microphone) are plugged in to an iOS device

using this and a if statement with your method below will get you your results.

 - (BOOL)isHeadsetPluggedIn {
    UInt32 routeSize = sizeof (CFStringRef);
    CFStringRef route;

    OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
                                              &routeSize,
                                              &route);

    /* Known values of route:
     * "Headset"
     * "Headphone"
     * "Speaker"
     * "SpeakerAndMicrophone"
     * "HeadphonesAndMicrophone"
     * "HeadsetInOut"
     * "ReceiverAndMicrophone"
     * "Lineout"
     */

    if (!error && (route != NULL)) {

        NSString* routeStr = (NSString*)route;

        NSRange headphoneRange = [routeStr rangeOfString : @"Head"];

        if (headphoneRange.location != NSNotFound) return YES;

    }

    return NO;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top