Search code examples
iphoneiosxcode4avfoundation

Routing audio input to receive from TOP microphone on iPhone


I am writing a little app to record multiple tracks and play them back over one another. I am using the PlaybackAndRecord mode and i am routing my output to the main speakers. Problem is that the bottom microphone is still being used for input as well so now I when I record I get the output from the other tracks really loud on the new track. Here is what I have so far:

audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];    
OSStatus propertySetError = 0;
UInt32 allowMixing = true;
propertySetError = AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(allowMixing), &allowMixing);

UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);

[audioSession setActive:YES error:nil];

Solution

  • Use AVAudioSession to get available inputs. On my iPhone 5 it looks like this.

    NSLog(@"%@", [AVAudioSession sharedInstance].availableInputs);
    
      "<AVAudioSessionPortDescription: 0x14554400, type = MicrophoneBuiltIn; name = iPhone Microphone; UID = Built-In Microphone; selectedDataSource = Back>"
    

    Then use one of these inputs to get availableDataSources, like this.

    NSLog(@"%@", [AVAudioSession sharedInstance].availableInputs[0].dataSources);
    
      "<AVAudioSessionDataSourceDescription: 0x145afb00, ID = 1835216945; name = Bottom>",
      "<AVAudioSessionDataSourceDescription: 0x145b1870, ID = 1835216946; name = Front>",
      "<AVAudioSessionDataSourceDescription: 0x145b3650, ID = 1835216947; name = Back>"
    

    We can see that there are actually THREE microphones on this iPhone: top front, top back, and bottom. Now you can set your preferred data source.

    AVAudioSessionPortDescription *port = [AVAudioSession sharedInstance].availableInputs[0];
    for (AVAudioSessionDataSourceDescription *source in port.dataSources) {
        if ([source.dataSourceName isEqualToString:@"Back"]) {
            [port setPreferredDataSource:source error:nil];
        }
    }