zhoutaifeng 2019-12-11
首先我们需要进行麦克风访问授权
AVAudioSessionRecordPermission permission = [[AVAudioSession sharedInstance] recordPermission];
//判断是否授权
if (AVAudioSessionRecordPermissionUndetermined == permission) {
[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
//授权回调操作
}];
} else {
//用户没有同意授权
}在授权成功之后再执行录音操作代码
//首先设置录音模式
AVAudioSession *session = [AVAudioSession sharedInstance];
NSError *sessionError;
/*
AVAudioSessionCategoryPlayAndRecord :录制和播放
AVAudioSessionCategoryAmbient :用于非以语音为主的应用,随着静音键和屏幕关闭而静音.
AVAudioSessionCategorySoloAmbient :类似AVAudioSessionCategoryAmbient不同之处在于它会中止其它应用播放声音。
AVAudioSessionCategoryPlayback :用于以语音为主的应用,不会随着静音键和屏幕关闭而静音.可在后台播放声音
AVAudioSessionCategoryRecord :用于需要录音的应用,除了来电铃声,闹钟或日历提醒之外的其它系统声音都不会被播放,只提供单纯录音功能.
*/
[session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
[session setActive:YES error:nil];
// 录音参数
NSDictionary *setting = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,// 编码格式
[NSNumber numberWithFloat:8000], AVSampleRateKey, //采样率
[NSNumber numberWithInt:1], AVNumberOfChannelsKey, //通道数
[NSNumber numberWithInt:16], AVLinearPCMBitDepthKey, //采样位数(PCM专属)
[NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved, //是否允许音频交叉(PCM专属)
[NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey, //采样信号是否是浮点数(PCM专属)
[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey, //是否是大端存储模式(PCM专属)
[NSNumber numberWithInt:AVAudioQualityMax], AVEncoderAudioQualityKey, //音质
nil];
NSString *filePath = @"";//设置录音文件的存储路径
self.recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:filePath] settings:setting error:nil];
self.recorder.delegate = self;
//开启音频测量
self.recorder.meteringEnabled = YES;
[self.recorder prepareToRecord];
[self.recorder record];结束录音方法
//结束播放
if (self.recorder != nil) {
[self.recorder stop];
}最后就可以在之前设置的录音文件路径目录读取音频数据
同时有个录音代理回调方法也可以处理
AVAudioRecorderDelegate
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
//录音技术操作
//录音模式结束后需要将模式调整回来
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
}
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error
{
//录音失败调用
}