iOS AVAudioSession - Microphone Selection

From

https://developer.apple.com/library/archive/qa/qa1799/_index.html

Code

#import 

- (void) demonstrateInputSelection
{
    NSError* theError = nil;
     BOOL result = YES;
    AVAudioSession* myAudioSession = [AVAudioSession sharedInstance];
    result = [myAudioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&theError];
    if (!result)
    {
        NSLog(@"setCategory failed");
    }
    result = [myAudioSession setActive:YES error:&theError];
    if (!result)
    {
        NSLog(@"setActive failed");
    }
    // Get the set of available inputs. If there are no audio accessories attached, there will be
    // only one available input -- the built in microphone.
    NSArray* inputs = [myAudioSession availableInputs];
   
// Locate the Port corresponding to the built-in microphone.
    AVAudioSessionPortDescription* builtInMicPort = nil;
    for (AVAudioSessionPortDescription* port in inputs)
    {
        if ([port.portType isEqualToString:AVAudioSessionPortBuiltInMic])
        {
            builtInMicPort = port;
            break;
        }
    }
// Print out a description of the data sources for the built-in microphone
NSLog(@"There are %u data sources for port :\"%@\"", (unsigned)[builtInMicPort.dataSources count], builtInMicPort);
NSLog(@"%@", builtInMicPort.dataSources);

// loop over the built-in mic's data sources and attempt to locate the front microphone
AVAudioSessionDataSourceDescription* frontDataSource = nil;
for (AVAudioSessionDataSourceDescription* source in builtInMicPort.dataSources)
{
    if ([source.orientation isEqual:AVAudioSessionOrientationFront])
    {
        frontDataSource = source;
        break;
    }
} // end data source iteration

if (frontDataSource)
{
    NSLog(@"Currently selected source is \"%@\" for port \"%@\"", builtInMicPort.selectedDataSource.dataSourceName, builtInMicPort.portName);
    NSLog(@"Attempting to select source \"%@\" on port \"%@\"", frontDataSource, builtInMicPort.portName);

    // Set a preference for the front data source.
    theError = nil;
    result = [builtInMicPort setPreferredDataSource:frontDataSource error:&theError];
    if (!result)
    {
        // an error occurred. Handle it!
        NSLog(@"setPreferredDataSource failed");
    }
}

// Make sure the built-in mic is selected for input. This will be a no-op if the built-in mic is
// already the current input Port.
theError = nil;
result = [myAudioSession setPreferredInput:builtInMicPort error:&theError];
if (!result)
{
    // an error occurred. Handle it!
    NSLog(@"setPreferredInput failed");
}

}

Following console output when run on an iPhone 5:

There are 3 data sources for port :""
(
    "",
    "",
    ""
)
Currently selected source is "Bottom" for port "iPhone Microphone"
Attempting to select source "" on port "iPhone Microphone”

你可能感兴趣的:(iOS AVAudioSession - Microphone Selection)