AvaudioRecorder 录音

//

//  ViewController.m

//  AVAudioRecorder录音

//

//  Created by 草帽~小子 on 2017/8/16.

//  Copyright © 2017年 HLJ. All rights reserved.

//

 

#import "ViewController.h"

#import

#define kRecordAudioFile @"myRecord.caf"

 

*************plist文件中添加媒体、相机、麦克风权限********

@interface ViewController ()<AVAudioRecorderDelegate>

 

@property (nonatomic,strong)AVAudioRecorder *audioRecorder;//音频录音机

@property (nonatomic,strong)AVAudioPlayer *audioPlayer;//音频播放器,用于播放录音文件

@property (nonatomic,strong)NSTimer *timer;//录音声波监控(注意这里暂时不对播放进行监控)

 

@property (strong,nonatomic) UIButton *record;//开始录音

@property (strong,nonatomic) UIButton *pause;//暂停录音

@property (strong,nonatomic) UIButton *resume;//恢复录音

@property (strong,nonatomic) UIButton *stop;//停止录音

@property (strong,nonatomic) UIProgressView *audioPower;//音频波动

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [superviewDidLoad];

    

    [selfcreateSub];

    [selfsetAudioSession];

    

    

    

    // Do any additional setup after loading the view, typically from a nib.

}

 

- (void)createSub {

    //录音

    self.record = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.record.frame =CGRectMake(10,500, 60,40);

    self.record.backgroundColor = [UIColor orangeColor];

    [self.recordsetTitle:@"录音"forState:UIControlStateNormal];

    [self.recordaddTarget:selfaction:@selector(record:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.record];

    //暂停

    self.pause = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.pause.frame =CGRectMake(80,500, 60,40);

    self.pause.backgroundColor = [UIColor orangeColor];

    [self.pausesetTitle:@"暂停"forState:UIControlStateNormal];

    [self.pauseaddTarget:selfaction:@selector(pause:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.pause];

    //恢复

    self.resume = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.resume.frame =CGRectMake(150,500, 60,40);

    self.resume.backgroundColor = [UIColor orangeColor];

    [self.resumesetTitle:@"恢复"forState:UIControlStateNormal];

    [self.resumeaddTarget:selfaction:@selector(resume:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.resume];

    //停止

    self.stop = [UIButtonbuttonWithType:UIButtonTypeSystem];

    self.stop.frame =CGRectMake(220,500, 60,40);

    self.stop.backgroundColor = [UIColor orangeColor];

    [self.stopsetTitle:@"停止"forState:UIControlStateNormal];

    [self.stopaddTarget:selfaction:@selector(stop:)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:self.stop];

}

 

#pragma mark - 私有方法

/**

 *  设置音频会话

 */

-(void)setAudioSession{

    AVAudioSession *audioSession=[AVAudioSessionsharedInstance];

    //设置为播放和录音状态,以便可以在录制完之后播放录音

    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecorderror:nil];

    [audioSession setActive:YESerror:nil];

}

 

/**

 *  取得录音文件保存路径

 *

 *  @return 录音文件路径

 */

-(NSURL *)getSavePath{

NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) lastObject];

    urlStr=[urlStr stringByAppendingPathComponent:kRecordAudioFile];

    NSLog(@"file path:%@",urlStr);

    NSURL *url=[NSURLfileURLWithPath:urlStr];

    return url;

}

 

/**

 *  取得录音文件设置

 *

 *  @return 录音设置

 */

-(NSDictionary *)getAudioSetting{

    NSMutableDictionary *dicM=[NSMutableDictionarydictionary];

    //设置录音格式

    [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;

}

 

/**

 *  获得录音机对象

 *

 *  @return 录音机对象

 */

-(AVAudioRecorder *)audioRecorder{

    if (!_audioRecorder) {

        //创建录音文件保存路径

        NSURL *url = [self getSavePath];

        //创建录音格式设置

        NSDictionary *setting = [self getAudioSetting];

        //创建录音机

        NSError *error =nil;

        _audioRecorder=[[AVAudioRecorderalloc]initWithURL:urlsettings:setting error:&error];

        _audioRecorder.delegate =self;

        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES

        if (error) {

            NSLog(@"创建录音机对象时发生错误,错误信息:%@",error.localizedDescription);

            returnnil;

        }

    }

    return_audioRecorder;

}

 

 

/**

 *  创建播放器

 *

 *  @return 播放器

 */

-(AVAudioPlayer *)audioPlayer{

    if (!_audioPlayer) {

        NSURL *url = [selfgetSavePath];

        NSError *error=nil;

        _audioPlayer=[[AVAudioPlayeralloc]initWithContentsOfURL:urlerror:&error];

        _audioPlayer.numberOfLoops=0;

        [_audioPlayerprepareToPlay];

        if (error) {

            NSLog(@"创建播放器过程中发生错误,错误信息:%@",error.localizedDescription);

            returnnil;

        }

    }

    return_audioPlayer;

}

 

 

/**

 *  录音声波监控定制器

 *

 *  @return 定时器

 */

-(NSTimer *)timer{

    if (!_timer) {

        _timer=[NSTimerscheduledTimerWithTimeInterval:0.1ftarget:selfselector:@selector(audioPowerChange)userInfo:nilrepeats:YES];

    }

    return_timer;

}

 

/**

 *  录音声波状态设置

 */

-(void)audioPowerChange{

    [self.audioRecorderupdateMeters];//更新测量值

    float power= [self.audioRecorderaveragePowerForChannel:0];//取得第一个通道的音频,注意音频强度范围时-160到0

    CGFloat progress=(1.0/160.0)*(power+160.0);

    [self.audioPowersetProgress:progress];

}

 

 

#pragma mark - UI事件

/**

 *  点击录音按钮

 *

 *  @param button 录音按钮

 */

 

- (void)record:(UIButton *)button {

    if (![self.audioRecorderisRecording]) {

        [self.audioRecorderrecord];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风

        self.timer.fireDate = [NSDatedistantPast];

    }

}

 

- (void)pause:(UIButton *)bu {

    if ([self.audioRecorderisRecording]) {

        [self.audioRecorderpause];

        self.timer.fireDate=[NSDatedistantFuture];

    }

}

 

 

- (void)resume:(UIButton *)bu {

    

    [selfrecord:bu];

    

}

 

- (void)stop:(UIButton *)bu {

    [self.audioRecorderstop];

    self.timer.fireDate=[NSDatedistantFuture];

    self.audioPower.progress=0.0;

}

 

#pragma mark - 录音机代理方法

/**

 *  录音完成,录音完成后播放录音

 *

 *  @param recorder 录音机对象

 *  @param flag     是否成功

 */

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{

    if (![self.audioPlayerisPlaying]) {

        [self.audioPlayerplay];

        NSLog(@"sdf");

    }

    NSLog(@"录音完成!");

}

 

 

你可能感兴趣的:(iOS)