How to select external microphone

前提是你 提交于 2021-02-18 08:13:27

问题


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.


回答1:


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



回答2:


You need to import AVFoundation for that. Using shared instance of AVAudioSession you can identify current route that is AVAudioSessionPortDescription will help you to identify port type.I believe you can not select particular mic but you can identify and check currentRoute of session

AVAudioSession *session = [AVAudioSession sharedInstance];
AVAudioSessionPortDescription *input = [[session.currentRoute.inputs count] ? session.currentRoute.inputs:nil objectAtIndex:0];

if ([input.portType isEqualToString:AVAudioSessionPortLineIn]) {
    NSLog(@"Audio Route: Input Port: LineIn");
}
else if ([input.portType isEqualToString:AVAudioSessionPortBuiltInMic]) {
    NSLog(@"Audio Route: Input Port: BuiltInMic");
}
else if ([input.portType isEqualToString:AVAudioSessionPortHeadsetMic]) {
    NSLog(@"Audio Route: Input Port: HeadsetMic");
}
else if ([input.portType isEqualToString:AVAudioSessionPortBluetoothHFP]) {
    NSLog(@"Audio Route: Input Port: BluetoothHFP");
}
else if ([input.portType isEqualToString:AVAudioSessionPortUSBAudio]) {
    NSLog(@"Audio Route: Input Port: USBAudio");
}
else if ([input.portType isEqualToString:AVAudioSessionPortCarAudio]) {
    NSLog(@"Audio Route: Input Port: CarAudio");
}
else {
    NSLog(@"Audio Input Port: Unknown: %@",input.portType);
}


来源:https://stackoverflow.com/questions/44194923/how-to-select-external-microphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!