·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> iOS耳机操作

iOS耳机操作

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

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

1
2
3
4
5
6
7
8
9
10
11
12
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检测耳机插入/拔出

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
- (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;
}