Switching between headphone & speaker on iPhone

2019-07-25 03:34发布

问题:

I am trying to set up the audio routing for an iPhone app outputting. I am using a route change listener to detect when the audio route has changed. The listener detects the changes, such as when the headphones are plugged in and out. By default, the speaker plays audio and then I plug my headphones in and the audio transmits through the headphones fine. From there, any changes do not occur, even though the route change listener is detecting them.

Any help would be really appreciated.

NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord
                                       error:&sessionError];
UInt32 sessionCategory = kAudioSessionCategory_PlayAndRecord;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory),
                        &sessionCategory);
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
                        sizeof(sessionCategory), &sessionCategory);
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange,
                            RouteChangeListener, (__bridge void *)(self));
AudioSessionSetActive(YES);

Callback listener:

void RouteChangeListener(
                         void                      *inUserData,
                         AudioSessionPropertyID    inPropertyID,
                         UInt32                    inPropertyValueSize,
                         const void                *inPropertyValue)
{
    if (inPropertyID == kAudioSessionProperty_AudioRouteChange) {
        CFStringRef newRoute;
        UInt32 size = sizeof(CFStringRef);
        AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &newRoute);
        if (newRoute) {
            CFShow(newRoute);
            if (CFStringCompare(newRoute, CFSTR("SpeakerAndMicrophone"),
                                (UInt32)NULL) == kCFCompareEqualTo) {
                UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
                AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                                         sizeof(audioRouteOverride), &audioRouteOverride);
            } else if (CFStringCompare(newRoute, CFSTR("HeadphonesAndMicrophone"),
                                       (UInt32)NULL) == kCFCompareEqualTo) {
                UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_None;
                AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
                                         sizeof(audioRouteOverride), &audioRouteOverride);
                    [[[AVAudioSession sharedInstance] player] play];
            }
        }
    }
}