监听耳机插拔设置语音播放重定向 & 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];
    }

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值