AduioSession 听筒扬声器切换

AduioSession 听筒扬声器切换

  • 对于AVAudioSessionCategoryPlayback ,默认是扬声器,而切换为AVAudioSessionCategoryPlayAndRecord,默认为听筒播放,
    则需要进行切换

PlayAndRecord下切换到扬声器

除了用户手动修改,也可以在程序里切换

1.修改Category的行为

   [_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionDefaultToSpeaker error:nil];

  1. 通过OverrideOutputAudioPort来修改
    
    [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];

监听用户切换输出设备

1.新增一个通知,object一定要为 [AVAudioSession sharedInstance] ,否则收不到通知

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:)
                                                    name:AVAudioSessionRouteChangeNotification
                                                  object:[AVAudioSession sharedInstance]];

2.处理通知,"Headphones"为iPhone耳机自带的麦克风

- (void)routeChange:(NSNotification*)notify{
    if(notify){
        NSLog(@"声音声道改变%@",notify);
    }
    AVAudioSessionRouteDescription *route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription * desc in [route outputs]) {
        NSLog(@"当前声道%@",[desc portType]);
        NSLog(@"输出源名称%@",[desc portName]);

        if ([[desc portType] isEqualToString:@"Headphones"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
            });
        }
    }
}

问题:但这切换在AVAudioSessionCategoryPlayAndRecord 模式下,如果同时响起闹钟的声音还是很小声,已经不为扬声器输出,问题还未解决

你可能感兴趣的:(AduioSession 听筒扬声器切换)