用AVAudioRecorder实现录音功能

时间:2022-03-05 18:18:40
创建一个AudioRecordController 的类

#import "AudioRecordController.h"
#import <AVFoundation/AVFoundation.h>    //导入AVFoundation/AVFoundation.h头文件

@interface AudioRecordController ()<AVAudioRecorderDelegate>
{
     AVAudioRecorder     *_recoder;
    IBOutlet UIProgressView *_progressView; //与storyboard 中的Progress View关联上
}

@property (nonatomic,strong) NSTimer    *timer;

@end

@implementation AudioRecordController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:nil];
    //Documents libary caches 三个目录在Search函数的第一个参数设置,其他参数固定就可以
    NSString *docmentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    
    //中转目录,调用PathComponent方法会在原有路径上加一个/,以下两种写法作用相同
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingString:@"/aaa.caf"];
    filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"aaa.caf"];
    [self recordAudioWithFilePath:filePath];
}

-(NSTimer *)timer
{
    if (!_timer)
    {
        //创建一个timer,每隔0.5秒执行一次,执行时会调用updatePower方法
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updatePower) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)updatePower
{
    //更新一下声波频率
    [_recoder updateMeters];
    //取到power,第一个通道的声波,声波强度范围是-160~0
    float power = [_recoder averagePowerForChannel:0];
    
    _progressView.progress = (power+160)/160.0;
}

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog(@"成功");
}

-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    NSLog(@"%@",error.localizedDescription);
}

-(void)recordAudioWithFilePath:(NSString *)filePath
{
    NSURL *url = [NSURL fileURLWithPath:filePath];
    
    //录音格式是caf,
    //采样频率8000 电话采用的采样频率,可识别人声没有问题 16000 24000 44100
    //通道数 单通道1 双通道2
    //采样位数 8位 16 24 32
    NSDictionary *settings = @{AVFormatIDKey:@(kAudioFormatLinearPCM),AVSampleRateKey:@(8000),AVNumberOfChannelsKey:@(1),AVLinearPCMBitDepthKey:@(8)};
    
    NSError *error = nil;
    
    _recoder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    
    if (!error)
    {
        _recoder.delegate = self;
        
        //我录音的声音大小在进度条中实时展示
        //记录声音的频率激活
        _recoder.meteringEnabled = YES;
    }
}

-(void)record
{
    //过去的日期是开始timer
    self.timer.fireDate = [NSDate distantPast];
    [_recoder record];
}

-(void)pause
{
    self.timer.fireDate = [NSDate distantFuture];
    [_recoder pause];
}

-(void)stop
{
    //停止的时候让timer失效,然后置为nil
    [self.timer invalidate];
    self.timer = nil;
    [_recoder stop];
}

-(IBAction)recordClick:(UIButton *)sender
{
    //暂停变播放,播放变暂停
    sender.selected = !sender.selected;
    if (sender.selected)
    {
        [self record];
    }
    else
    {
        [self pause];
    }
}

-(IBAction)stopClick:(id)sender
{
    [self stop];
}