如何确定录音源

时间:2011-05-25 12:39:47

标签: iphone objective-c ipad audio audio-recording

使用我的iPad应用程序录制声音时,如何知道声源是来自内置麦克风还是耳机麦克风?

其他信息:iOS 4.2及更高版本。

1 个答案:

答案 0 :(得分:0)

确定这一点的方法是轮询硬件并查询当前的音频路径。

使用AudioSessionGetProperty对象取回音频路径。

example by @TPoschel应该让您走上正确的轨道。

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