录音

作者: lcc小莫 | 来源:发表于2018-05-07 16:32 被阅读0次

AVAudioRecorder是录音必须要用的,其次就是要设置录音的路径,存放在本地,之后的播放或者说上传都通过此路劲进行进行操作。

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

#define kRecordAudioFile @"myRecord.caf"

@interface ViewController ()<AVAudioRecorderDelegate>

@property (nonatomic,strong)AVAudioRecorder * audioRecorder;//音频录音机
@property (nonatomic,strong)AVAudioPlayer   * audioPlayer;//音频播放器,用于播放录音
@property (nonatomic,strong)NSTimer         * timer;//录音声波监控;
@property (nonatomic,strong)UIProgressView  * audioPower;//进度条

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];

    [self setAudioSession];

    [self.view addSubview:self.audioPower];
}
懒加载音频对象和音频播放器
/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder * )audioRecorder
{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL * url =[self getSavePath];
        //创建录音格式设置
        NSDictionary * setting = [self getAudioSettion];
        //创建录音机
        NSError * error = nil;
        _audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled = YES;//如果要控制声波则必须设置为YES
        if(error)
        {
            NSLog(@"创建录音机对象发生错误,错误信息是:%@",error.localizedDescription);
            return nil;
        }
        [self.audioRecorder prepareToRecord];
        }
    return _audioRecorder;
}
/**
 *  创建播放器
 *
 *  @return 播放器
 */
-(AVAudioPlayer *)audioPlayer
{
    if (!_audioPlayer) {
        NSURL * url = [self getSavePath];
        NSError * error = nil;
        _audioPlayer =[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        _audioPlayer.numberOfLoops = 0;
        [_audioPlayer prepareToPlay];
        if (error) {
            NSLog(@"创建播放器过程出错:错误信息是:%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}
设置音频会话
  -(void)setAudioSession
  {
      AVAudioSession * audioSession = [AVAudioSession sharedInstance];
      //设置为播放和录制状态,以便在录制完成之后播放录音
      [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
      [audioSession setActive:YES error:nil];
  }
取得录音文件的保存路径
-(NSURL *)getSavePath
{
    NSString * urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES ) lastObject];
    urlStr = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    NSLog(@"file:path:%@",urlStr);
    NSURL * url = [NSURL fileURLWithPath:urlStr];
    return url;
}
取得录音文件的设置
-(NSDictionary *)getAudioSettion
{
    NSMutableDictionary * dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率,8000是电话采样率,对于一般的录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8,16,24,32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //。。。。是他设置
    return dicM;
}
监控声波在进度条上显示
-(UIProgressView *)audioPower {
if (!_audioPower) {
    
    //进度条高度不可修改
    _audioPower = [[UIProgressView alloc] initWithFrame:CGRectMake(100, 400, 200, 40)];
    
    //设置进度条的颜色
    _audioPower.progressTintColor = [UIColor blueColor];
    
    //设置进度条的当前值,范围:0~1;
    _audioPower.progress = 0.5;
    
    /*
     typedef NS_ENUM(NSInteger, UIProgressViewStyle) {
     UIProgressViewStyleDefault,     // normal progress bar
     UIProgressViewStyleBar __TVOS_PROHIBITED,     // for use in a toolbar
     };
     */
    _audioPower.progressViewStyle = UIProgressViewStyleDefault;
    
    _audioPower.layer.borderWidth = 0.5;
}
return _audioPower;
}
/**
 *  录音声波监控定时器
 *
 *  @return 定时器
 */
-(NSTimer * )timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(void)audioPowerChange
{
    [self.audioRecorder updateMeters];//跟新检测值
    float power = [self.audioRecorder averagePowerForChannel:0];//获取第一个通道的音频,注音音频的强度方位-160到0
    CGFloat progerss = (1.0/160)*(power+160);
    [self.audioPower setProgress:progerss];
}
#pragma mark - 按钮点击事件
/*开始录音*/
- (IBAction)startRecording:(id)sender {
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];
        self.timer.fireDate = [NSDate distantPast];
    }
}
/*结束录音*/
- (IBAction)endRecording:(id)sender {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
        self.timer.fireDate = [NSDate distantFuture];
        self.audioPower.progress = 0.0;
    }
}
/**
 *  点击恢复按钮
 *  恢复录音只需要再次调用record,AVAudioSession会帮助你记录上次录音位置并追加录音
 *
 *  @param sender 恢复按钮
 */
- (IBAction)resumeClick:(id)sender {
    [self startRecording:sender];
}

/**
 *  点击暂停按钮
 *
 *  @param sender 暂停按钮
 */
- (IBAction)stopClick:(id)sender {
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder pause];
        self.timer.fireDate=[NSDate distantFuture];
    }
}
#pragma mark - 录音机代理方法
/**
 *  录音完成,录音完成后播放录音
 *  @param recorder 录音机对象
 *  @param flag     是否成功
 */
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"录音完成!");

    if (![self.audioPlayer isPlaying]) {
        [self.audioPlayer play];
    
        NSLog(@"播放录音!");
    }
}

相关文章

网友评论

      本文标题:录音

      本文链接:https://www.haomeiwen.com/subject/kokvrftx.html