录音的基本使用

//
//  ViewController.m

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

@interface ViewController ()
- (IBAction)startRecord;
- (IBAction)stopRecord;


/**
 *  录音器
 */
@property (nonatomic, strong) AVAudioRecorder *recorder;
/**
 *  定时器
 */
@property (nonatomic, strong) CADisplayLink *link;
/**
 *  声音沉默时间
 */
@property (nonatomic, assign) double slientDuration;
@end

@implementation ViewController

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

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

- (void)update
{
    // 1.更新录音器的测量值
    [self.recorder updateMeters];
    
    // 2.获得平均分贝
    float power = [self.recorder averagePowerForChannel:0];
    
    // 3.如果小于-30, 开始静音
    if (power < - 30) {
        //        [self.recorder pause];
        
        self.slientDuration += self.link.duration;
        
        if (self.slientDuration >= 2) { // 沉默至少2秒钟
            [self.recorder stop];
            
            // 停止定时器
            [self.link invalidate];
            self.link = nil;
            NSLog(@"--------停止录音");
        }
    } else {
        //        [self.recorder record];
        self.slientDuration = 0;
        NSLog(@"**********持续说话");
    }
}


/**
 *  开始录音
 */
- (IBAction)startRecord {
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.caf"];
    NSURL *url = [NSURL fileURLWithPath:path];
    
    // 1.创建录音器
    NSMutableDictionary *setting = [NSMutableDictionary dictionary];
    // 音频格式
    setting[AVFormatIDKey] = @(kAudioFormatAppleIMA4);
    // 音频采样率
    setting[AVSampleRateKey] = @(8000.0);
    // 音频通道数
    setting[AVNumberOfChannelsKey] = @(1);
    // 线性音频的位深度
    setting[AVLinearPCMBitDepthKey] = @(8);
    AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:nil];
    
    // 允许测量分贝
    recorder.meteringEnabled = YES;
    
    // 2.缓冲
    [recorder prepareToRecord];
    
    // 3.录音
    [recorder record];
    
    self.recorder = recorder;
    
    // 4.开启定时器
    self.slientDuration = 0;
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

}

/**
 *  停止录音
 */
- (IBAction)stopRecord {
     [self.recorder stop];
}


@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值