1、引入头文件
#import <AVFoundation/AVFoundation.h>
2、声明属性
@property (nonatomic, strong) AVAudioRecorder *recorder; //录制器
@property (nonatomic, strong) NSString *path; // 录音存放位置
3、初始化
- (AVAudioRecorder *)recorder {
if (_recorder == nil) {
// 创建录音对象
// 0.创建录音会话
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[session setActive:YES error:nil];
// 1.设置录音参数
NSMutableDictionary *recordSettings = [NSMutableDictionary dictionary];
// 音频编码格式
[recordSettings setValue:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
// 采样率(HZ) 8000/96000/11025/22050/44100
[recordSettings setValue:@(11025) forKey:AVSampleRateKey];
// 音频通道数 1/2
[recordSettings setValue:@(1) forKey:AVNumberOfChannelsKey];
// 采样位数 8、16、32 默认为16
[recordSettings setValue:@(16) forKey:AVLinearPCMBitDepthKey];
// 音频质量
[recordSettings setValue:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
// 2.确定录音存放的位置
NSURL *url = [[NSURL alloc] initFileURLWithPath:self.path];
// 3.创建录音对象
NSError *error = nil;
_recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSettings error:&error];
if (error) {
return nil;
}
}
return _recorder;
}
遵守协议AVAudioRecorderDelegate
#pragma mark - <AVAudioRecorderDelegate>
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
}
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
}
4、
// 判断麦克风权限
- (void)micPhonePermissions:(void (^)(BOOL ishave))block {
__block BOOL ret = NO;
AVAudioSession *session = [AVAudioSession sharedInstance];
if ([session respondsToSelector:@selector(requestRecordPermission:)]) {
[session requestRecordPermission:^(BOOL available) {
if (available) {
ret = YES;
}
dispatch_async(dispatch_get_main_queue(), ^{
if (block) {
block(ret);
}
});
}];
}
}
// 开始录音
- (void)startAudioRecord {
// 判断麦克风权限
[self micPhonePermissions:^(BOOL ishave) {
if (ishave) {
if ([self.recorder prepareToRecord]) {
[self.recorder record];
}
} else {
if (self.delegate && [self.delegate respondsToSelector:@selector(audioRecorderFailed:)]) {
[self.delegate audioRecorderFailed:@"请在“设置-隐私-麦克风”中允许访问麦克风"];
}
}
}];
}
// 停止录音
- (void)stopAudioRecord {
if (self.recorder) {
[self.recorder stop];
self.recorder = nil;
}
if ([[NSFileManager defaultManager] fileExistsAtPath:self.path]) {
NSLog(@"录音文件:%.2fKB", [[[NSFileManager defaultManager] attributesOfItemAtPath:self.path error:nil] fileSize] / 1024.0);
}
}
// 删除录音
- (void)deleteAudioRecord {
if (self.recorder) {
[self.recorder stop];
[self.recorder deleteRecording];
self.recorder = nil;
}
}