说明:
使用AVAudioRecorder录音
一、开始录音:
//录音器成员变量
@property (nonatomic, strong) AVAudioRecorder *recorder;
/*
1.开始录音
*/
- (void)startRecord{
//1.录音保存文件路径
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"20190413080101.aac"];
//url
NSURL *url = [NSURL fileURLWithPath:filePath];
//2.创建集合,配置录音设置
NSMutableDictionary *map = [self genRecorderSet];
//3.创建录音器
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:map error:nil];
//允许测量分贝
recorder.meteringEnabled = YES;
//4.缓冲
[recorder prepareToRecord];
//5.开始录音
[recorder record];
//存为成员变量,方便停止暂停操作
self.recorder = recorder;
//开始定时监听分贝
[self.dl addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
}
/*
创建集合,配置录音设置
*/
- (NSMutableDictionary *)genRecorderSet{
//3.创建集合,配置录音设置
NSMutableDictionary *map = [NSMutableDictionary dictionary];
//格式
map[AVFormatIDKey] = @(kAudioFormatMPEG4AAC);
//采样率
map[AVSampleRateKey] = @(8000.0);
//通道数
map[AVNumberOfChannelsKey] = @(1);
//位深度
map[AVLinearPCMBitDepthKey] = @(8);
return map;
}
二、暂停录音:
2.暂停录音
*/
- (void)pauseRecord{
//判断是否在录音,不是则返回
if(![self.recorder isRecording]){
return;
}
//暂停
[self.recorder pause];
}
三、停止录音:
/*
3.停止录音
*/
- (void)stopRecord{
//判断是否在录音,不是则返回
if(![self.recorder isRecording]){
return;
}
//停止
[self.recorder stop];
}
四、监听说话分贝:
1.初始化定时器:
//定时器,实时监听分贝值
@property (nonatomic, strong) CADisplayLink *dl;
/*
懒加载,初始化定时器
*/
- (CADisplayLink *)dl{
if(_dl == nil){
//创建定时器
_dl = [CADisplayLink displayLinkWithTarget:self selector:@selector(onMetering)];
}
return _dl;
}
2.实时获取当前分贝值:
/*
被定时器实时调用
*/
- (void)onMetering{
//更新测量值
[self.recorder updateMeters];
//获取分贝
float decibel = [self.recorder averagePowerForChannel:0];
}
3.允许测量分贝,开启定时器:
//允许测量分贝
recorder.meteringEnabled = YES;
//开始定时监听分贝
[self.dl addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];