Search code examples
iosipadswift3core-audioaudio-recording

How to select external microphone


I've successfully written a simple recording app for iOS that uses AVAudioRecorder. So far it works with either the internal microphone or an external microphone if it's plugged in to the headphone jack. How do I select an audio source that is connected through the USB "lightning port"? Do I have to dive into Core Audio?

Specifically I'm trying to connect an Apogee Electronics ONE USB audio interface.


Solution

  • Using AVAudioSession, get the availableInputs. The return value is an array of AVAudioSessionPortDescriptions. Iterate through the array checking the portType property to match your preferred port type, then set the preferredInput using the port description.

    Swift:

    let audioSession = AVAudioSession.sharedInstance()
    if let desc = audioSession.availableInputs?.first(where: { (desc) -> Bool in
        return desc.portType == AVAudioSessionPortUSBAudio
    }){
        do{
            try audioSession.setPreferredInput(desc)
        } catch let error{
            print(error)
        }
    }
    

    Objective-C:

    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSString *preferredPortType = AVAudioSessionPortUSBAudio;
    for (AVAudioSessionPortDescription *desc in audioSession.availableInputs) {
        if ([desc.portType isEqualToString: preferredPortType]) {
            [audioSession setPreferredInput:desc error:nil];            
        }
    }