如何使用 AVFoundation 在音频输入源(蓝牙、内置麦克风)之间切换

How to switch between audio input source(Bluetooth, BuiltIn Microphone) using AVFoundation

我目前在内置麦克风和蓝牙麦克风之间切换音频输入源时遇到问题,iOS8

我试图找到在线解决方案,但一无所获:(

任何人,请告诉我正确的实现方法。

期待您的帮助!

我有这个代码。

bluetoothInput 只是一个布尔值,用于在蓝牙麦克风和普通麦克风之间切换。

-(void) changeBluetoothInput{


if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    if(self.bluetoothInput){
        //[[AVAudioSession sharedInstance] setActive:NO error:nil];

        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        AVAudioSessionPortDescription* _bluetoothPort = [self bluetoothAudioDevice];
        [[AVAudioSession sharedInstance] setPreferredInput:_bluetoothPort
                                                     error:nil];
    }else{
        //[[AVAudioSession sharedInstance] setActive:NO error:nil];
        //[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
        [[AVAudioSession sharedInstance] setActive:YES error:nil];
        AVAudioSessionPortDescription* _bluetoothPort = [self normalAudioDevice];
        [[AVAudioSession sharedInstance] setPreferredInput:_bluetoothPort
                                                     error:nil];
    }
}

}

- (AVAudioSessionPortDescription*)bluetoothAudioDevice
{
    NSArray* bluetoothRoutes = @[AVAudioSessionPortBluetoothA2DP, AVAudioSessionPortBluetoothLE, AVAudioSessionPortBluetoothHFP];
    return [self audioDeviceFromTypes:bluetoothRoutes];
}

- (AVAudioSessionPortDescription*)normalAudioDevice
{
    NSArray* bluetoothRoutes = @[AVAudioSessionPortBuiltInMic];
    return [self audioDeviceFromTypes:bluetoothRoutes];
}


- (AVAudioSessionPortDescription*)audioDeviceFromTypes:(NSArray*)types
{
    NSArray* routes = [[AVAudioSession sharedInstance] availableInputs];
    for (AVAudioSessionPortDescription* route in routes)
    {
        if ([types containsObject:route.portType])
        {
            return route;
        }
    }
    return nil;
}