监听耳机插拔设置语音播放重定向 & WebRTC & 音频播放路由初始化

最近发现一种情况:当耳机插入的时候,如果启动使用音频设置播放路由模式为speaker的话不起作用。要监听耳机插拔,重新设置。

使用WebRTC音频功能,设置播放重定向的前提貌似是需要有语音在播放,所以在WebRTC设置时,收到有语音数据过来,然后设置播放路由(算是初始化)。然后在APP代码层做监听耳机插拔设置播放重定向解决由于耳机引起的一些问题。

//首先设置监听
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:) name:AVAudioSessionRouteChangeNotification object:nil];


/**
 监听影响语音播放的状态变化
 @param isLoudSpeaker
 */
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
//            NSLog(@"AVAudioSessionRouteChangeReasonNewDeviceAvailable");
            [self p_audioPropertySet:NO];
            NSLog(@"耳机插入");
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
//            NSLog(@"AVAudioSessionRouteChangeReasonOldDeviceUnavailable");
            NSLog(@"耳机拔出,停止播放操作");
            [self p_audioPropertySet:YES];
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
}
- (void)p_audioPropertySet:(BOOL)isLoudSpeaker
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *error = nil;

    if(isLoudSpeaker)
    {

        if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker error:&error])
        {
            NSLog(@"AudioSession set mode error %@", error);
        }
        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
    }
    else
    {
        if (![audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionAllowBluetooth | AVAudioSessionCategoryOptionAllowBluetoothA2DP | AVAudioSessionCategoryOptionMixWithOthers error:&error])
        {
            NSLog(@"AudioSession set mode error %@", error);
        }

        [audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:&error];
    }

}

你可能感兴趣的:(iOS)