在耳机之间切换; iPhone上的扬声器

时间:2013-02-28 05:55:04

标签: ios audio avfoundation avplayer audiotoolbox

我正在尝试为iPhone应用输出设置音频路由。我正在使用路由更改侦听器来检测音频路由何时发生了变化。听众检测到变化,例如耳机插入和拔出时。默认情况下,扬声器播放音频,然后我插入耳机,音频通过耳机传输。从那里,即使路由更改侦听器正在检测它们,也不会发生任何更改。

任何帮助都会非常感激。

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);

回调监听器:

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];
            }
        }
    }
}

0 个答案:

没有答案