iOS录音

CZViewController.m

#import "CZViewController.h"
#import 
@interface CZViewController ()
@property (nonatomic,strong)AVAudioRecorder *recorder;
@property (nonatomic,strong)CADisplayLink *link;
@property (nonatomic,assign)double chenmoTime;
@end

@implementation CZViewController

- (CADisplayLink *)link
{
    if (!_link) {
        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
    }
    return _link;
}

- (void)update
{
    //目标:  不停的看 当前的分贝数
    [self.recorder updateMeters];
    float power =  [self.recorder averagePowerForChannel:0];
    NSLog(@"====%f==== ",power);
    //需求  沉默两秒 停止录音
    if ( power <-30 ) { //  没有说话
        self.chenmoTime += self.link.duration;
        if (self.chenmoTime > 2) {
            [self.recorder stop];
            [self.link invalidate];
            self.link = nil;
        }
    }else {
        self.chenmoTime = 0;
    }
}

- (IBAction)start:(id)sender {
    //1.创建 录音对象
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@",path);
    NSString *urlStr = [path stringByAppendingString:@"/123.caf"];
    //注意点:  本地的文件路径用 fileURLWithPath 生成一个url
    NSURL *url = [NSURL fileURLWithPath:urlStr];
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    //2.够着  录音参数
    // 音频格式
    setting[AVFormatIDKey] = @(kAudioFormatAppleIMA4);
    // 音频采样率
    setting[AVSampleRateKey] = @(8000.0);
    // 音频通道数
    setting[AVNumberOfChannelsKey] = @(1);
    // 线性音频的位深度
    setting[AVLinearPCMBitDepthKey] = @(8);
    AVAudioRecorder *recorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:nil];
    self.recorder = recorder;    
    [recorder prepareToRecord];
    [recorder record];
    //分贝
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    //允许获取当前
    self.recorder.meteringEnabled = YES;
}
- (IBAction)end:(id)sender {
    [self.recorder stop];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}

你可能感兴趣的:(iOS录音)