IOS 录音(AVAudioRecorder)

Posted 守望星空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS 录音(AVAudioRecorder)相关的知识,希望对你有一定的参考价值。

 

 

#import "HMViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface HMViewController ()
- (IBAction)startRecord;
- (IBAction)stopRecord;
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) CADisplayLink *timer;
@property (nonatomic, strong) NSTimer *stopRecordTimer;
/** 静音的持续时间 */
@property (nonatomic, assign) CGFloat slientDuration;
@end

@implementation HMViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
}

- (void)addTimer
{
    self.timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
    [self.timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)removeTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)update
{
    // 更新测试值
    [self.recorder updateMeters];
    
    // 如果分贝不超过-20
    float power = [self.recorder averagePowerForChannel:0];
    if (power <= -20) { // 几乎为静音
        self.slientDuration += self.timer.duration;
        
        if (self.slientDuration >= 2) {
            // 停止录音
            [self.recorder stop];
        }
    } else { // 有说话
        self.slientDuration = 0;
        
    }
}

//- (void)update
//{
//    // 更新测试值
//    [self.recorder updateMeters];
//    
//    // 如果分贝不超过-20
//    float power = [self.recorder averagePowerForChannel:0];
//    if (power <= -20) { // 几乎为静音
//        if (!self.stopRecordTimer) {
//            self.stopRecordTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self.recorder selector:@selector(stopRecord) userInfo:nil repeats:NO];
//        }
//    } else { // 有说话
////        [self.stopRecordTimer invalidate];
////        self.stopRecordTimer = nil;
//        NSDate *time = [NSDate dateWithTimeIntervalSinceNow:2.0];
//        [self.stopRecordTimer setFireDate:time];
//    }
//}

- (IBAction)startRecord {
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [doc stringByAppendingPathComponent:@"test.caf"];
    NSURL *url = [NSURL fileURLWithPath:path];
    
    AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:nil error:nil];
    // 缓冲
    [recorder prepareToRecord];
    // 开启分贝测量功能
    recorder.meteringEnabled = YES;
    // 开始录音
    [recorder record];
    self.recorder = recorder;
    
    // 开启定时器
    [self addTimer];
}

- (IBAction)stopRecord {
//    [self.recorder stop];
}
@end

 

以上是关于IOS 录音(AVAudioRecorder)的主要内容,如果未能解决你的问题,请参考以下文章

AVAudioRecorder 不保存录音

AVAudioRecorder 设置录音开始时间

为啥 deleteRecording 崩溃(AVAudioRecorder,iOS)?

AVAudioRecorder 从不录音

iPhone - 使用 AVAudioRecorder 录音

Swift + AVAudioRecorder 非常安静地录制