当前位置: 动力学知识库 > 问答 > 编程问答 >

iphone - How to determine sound recording source

问题描述:

While recording a sound using my iPad app, how can I know if the source of the sound is from the built-in microphone or headphone microphone?

Additional information: iOS ver 4.2 and above.

网友答案:

The way to determine this is to poll the hardware and query the current audio route.

Use the AudioSessionGetProperty object to get back the route of the audio.

This example by @TPoschel should set you on the right track.

- (void)playSound:(id) sender
{
    if(player){

        CFStringRef route;
        UInt32 propertySize = sizeof(CFStringRef);
        AudioSessionInitialize(NULL, NULL, NULL, NULL);
        AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &route);

        if((route == NULL) || (CFStringGetLength(route) == 0)){
            // Silent Mode
            NSLog(@"AudioRoute: SILENT");
        } else {
            NSString* routeStr = (NSString*)route;
            NSLog(@"AudioRoute: %@", routeStr);

            /* Known values of route:
             * "Headset"
             * "Headphone"
             * "Speaker"
             * "SpeakerAndMicrophone"
             * "HeadphonesAndMicrophone"
             * "HeadsetInOut"
             * "ReceiverAndMicrophone"
             * "Lineout"
             */

            NSRange headphoneRange = [routeStr rangeOfString : @"Headphone"];
            NSRange headsetRange = [routeStr rangeOfString : @"Headset"];
            NSRange receiverRange = [routeStr rangeOfString : @"Receiver"];
            NSRange speakerRange = [routeStr rangeOfString : @"Speaker"];
            NSRange lineoutRange = [routeStr rangeOfString : @"Lineout"];

            if (headphoneRange.location != NSNotFound) {
                // Don't change the route if the headphone is plugged in.
            } else if(headsetRange.location != NSNotFound) {
                // Don't change the route if the headset is plugged in.
            } else if (receiverRange.location != NSNotFound) {
                // Change to play on the speaker
                UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
                AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
            } else if (speakerRange.location != NSNotFound) {
                // Don't change the route if the speaker is currently playing.
            } else if (lineoutRange.location != NSNotFound) {
                // Don't change the route if the lineout is plugged in.
            } else {
                NSLog(@"Unknown audio route.");
            }
        }

        [player play];
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: