码迷,mamicode.com
首页 > 移动开发 > 详细

IOS 录音(AVAudioRecorder)

时间:2017-05-22 23:24:04      阅读:876      评论:0      收藏:0      [点我收藏+]

标签:append   ann   oat   power   move   logs   imp   domain   scheduled   

 

 

#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)

标签:append   ann   oat   power   move   logs   imp   domain   scheduled   

原文地址:http://www.cnblogs.com/liuwj/p/6891605.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!