bryanjclark
bryanjclark

Reputation: 6404

How do I connect AVAudioEngine to a Lightning Port audio input?

I'd like to connect my electric guitar to my app. I have hardware (the Line6 Sonic Port) that passes the audio from my guitar into my iPhone. I've figured out how to get audio playing out to my headphones, but it's audio coming from my headphone mic, not the Lightning Port input. How do I programmatically find the Lightning Port audio input, instead of getting audio via the headphone mic?

Here's what I've tried so far:

self.audioEngine = AVAudioEngine()

let input = self.audioEngine.inputNode
let mixer = self.audioEngine.mainMixerNode
let output = self.audioEngine.outputNode

self.audioEngine.inputNode.installTapOnBus(0, bufferSize: 128, format: input.inputFormatForBus(0)) { (buffer, time) -> Void in
    //
}

self.audioEngine.connect(input, to: mixer, format: input.inputFormatForBus(0))
self.audioEngine.connect(mixer, to: output, format: mixer.inputFormatForBus(0))

self.audioEngine.prepare()
self.audioEngine.startAndReturnError(nil)

When I run this, I hear audio - but it's coming from my headphone mic, not the guitar. How can I connect to audio coming from the lightning port?

For a quick illustration, here is the hardware that I'm using: Line6 Sonic Port

Upvotes: 7

Views: 2302

Answers (2)

bryanjclark
bryanjclark

Reputation: 6404

To connect to a particular audio input, you need to configure the sharedInstance of AVAudioSession, by using the setPreferredInput:error: method.

Here's how this is done in Objective-C:

AVAudioSession *sharedSession = [AVAudioSession sharedInstance];
NSArray *availableInputs = [sharedSession availableInputs];
[availableInputs enumerateObjectsUsingBlock:^(AVAudioSessionPortDescription *portDescription, NSUInteger idx, BOOL *stop) {
    if (portDescription.portType == AVAudioSessionPortUSBAudio) {
        [sharedSession setPreferredInput:portDescription error:nil];
    }
}];

To learn more, check out:

Upvotes: 5

hotpaw2
hotpaw2

Reputation: 70703

iOS normally routes both audio input and output from the last port that was plugged in. Since you plugged in headphones, that's the port it uses for recording. Unplug the headphones, plug in lightning, and it will use that route for both audio record and play.

Upvotes: 2

Related Questions