Marko Markov
Marko Markov

Reputation: 23

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

I am currently having trouble with audio input source switching between builtInMicrophone and bluetooth microphone, iOS8

I tried to find online solutions, but got nothing :(

Anyone, please advice me proper way to achieve.

Looking forwards your help!

Upvotes: 2

Views: 1187

Answers (1)

Pablo Martinez
Pablo Martinez

Reputation: 1639

I've got this code.

bluetoothInput is just a boolean to switch between bluetooth mic and normal mic.

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

Upvotes: 1

Related Questions