#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