首页 > 代码库 > iOS耳机操作

iOS耳机操作

iOS在7之后增加的麦克风权限的申请,代码如下:

123456789101112
AVAudioSession *avSession = [AVAudioSession sharedInstance];if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {    [avSession requestRecordPermission:^(BOOL available) {        if (available) {            // 有麦克风权限        } else {            dispatch_async(dispatch_get_main_queue(), ^{                [[[UIAlertView alloc] initWithTitle:@"无法录音" message:@"请在“设置-隐私-麦克风”选项中允许xx访问你的麦克风" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];            });        }    }];}

iphone检测耳机插入/拔出

判断手机当前是否使用的是内置的麦克风(可以用此方法判断插入的耳机是否有麦克风)

123456789101112131415161718192021222324252627282930313233
- (BOOL)isCurrentUsingBuildInMicrophone{    NSError *error = nil;    BOOL result = YES;    result = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];    if (!result) {        NSLog(@"%@", error);        return YES;    }    result = [[AVAudioSession sharedInstance] setActive:YES error:&error];    if (!result) {        NSLog(@"setActive failed");        return YES;    }    CFDictionaryRef ards;    UInt32 size = sizeof(CFDictionaryRef);    OSStatus os = AudioSessionGetProperty(kAudioSessionProperty_AudioRouteDescription, &size, &ards);    if (os == kAudioSessionNoError && ards && CFDictionaryGetValue(ards, kAudioSession_AudioRouteKey_Inputs)) {        NSArray *inputs = (__bridge NSArray *)CFDictionaryGetValue(ards, kAudioSession_AudioRouteKey_Inputs);        if (inputs && inputs.count > 0) {            for (NSDictionary *dic in inputs) {                NSString *type = dic[(__bridge NSString *)kAudioSession_AudioRouteKey_Type];                if ([type isEqualToString:(__bridge NSString *)kAudioSessionInputRoute_BuiltInMic]) {                    return YES;                }            }        }    } else {        // 耳机没有mic        return YES;    }    return NO;}

iOS耳机操作