iOS:录音

说明:

使用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];

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值