- (BOOL)checkMicrophonePermission{
// AVAudioSessionRecordPermission permission = [[AVAudioSession sharedInstance] recordPermission];
// return permission == AVAudioSessionRecordPermissionGranted;
__block BOOL bCanRecord = NO;
if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
[audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
if (granted) {//用户选择允许
bCanRecord = YES;
NSLog(@"用户选择“允许”打开麦克风权限");
dispatch_async(dispatch_get_main_queue(), ^{
[self startRecordAudioSetup];
});
if (self.delegate && [self.delegate respondsToSelector:@selector(clickAllowOpenMicrophoneAuthorization)]) {
[self.delegate clickAllowOpenMicrophoneAuthorization];
}
} else {//用户选择不允许
bCanRecord = NO;
NSLog(@" 用户选择“不允许”打开麦克风权限");
[self popUpMicrophonePermissionAlertView];//弹出自己自定义的窗
if (self.delegate && [self.delegate respondsToSelector:@selector(clickNotAllowOpenMicrophoneAuthorization)]) {
[self.delegate clickNotAllowOpenMicrophoneAuthorization];
}
}
}];
}
} else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {
bCanRecord = NO;//用户在第一次系统弹窗后选择不允许之后,再次录音的时候会走这里“麦克风权限未授权”
// 未授权
NSLog(@"未授权");
[self popUpMicrophonePermissionAlertView];//弹出自己自定义的窗
if (self.delegate && [self.delegate respondsToSelector:@selector(microphoneUnauthorized)]) {
[self.delegate microphoneUnauthorized];
}
} else{
bCanRecord = YES;
// 已授权
NSLog(@"已授权");
[self startRecordAudioSetup];
if (self.delegate && [self.delegate respondsToSelector:@selector(microphoneAuthorized)]) {
[self.delegate microphoneAuthorized];
}
}
}
return bCanRecord;
}
//弹出自定义开启麦克风权限的提示框
- (void)popUpMicrophonePermissionAlertView{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"麦克风权限未开启"message:@"麦克风权限未开启,请进入系统【设置】>【隐私】>【麦克风】中打开开关,开启麦克风功能" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSLog(@"确定");
//跳入当前App设置界面
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];
});
}