简单粗暴的录音、播放功能

参考:http://blog.csdn.net/u013346305/article/details/47280731#t8

代码看下面,需要看效果的话直接复制到控制器即可,注意的是本案例采用storyboard布置界面,需要自己往ViewController里面拖拽几个UIBarButtonItem,并对UIBarButtonItem对应的方法连线。
【简单粗暴的录音、播放功能】注意以下是AVAudioRecorder文件里面主要的属性、对象方法、代理方法,并不是全部的,如有需要还得AVAudioRecorder.h中查看完整的属性、对象方法、代理方法。
属性 说明
@property(readonly, getter=isRecording) BOOL recording; 是否正在录音,只读
@property(readonly) NSURL *url; 录音文件存储地址,只读
@property(readonly) NSDictionary *settings; 录音文件设置, 只读
@property(readonly) NSTimeInterval currentTime; 录音时长,注意仅仅在录音状态可用
@property(readonly) NSTimeInterval deviceCurrentTime; 输入设置的时间长度,只读 注意此属性一直可访问
@property(getter=isMeteringEnabled) BOOL meteringEnabled; 是否启用录音测量 ,如果启用录音测量可以获得录音分贝等数据信息
@property(nonatomic, copy) NSArray *channelAssignments; 当前录音的通道
对象方法 说明
- (instancetype)initWithURL:(NSURL *)url settings:(NSDictionary *)settings error:(NSError **)outError; 录音机对象初始化方法,注意其中的url必须是本地文件url,settings是录音格式、编码等设置
- (BOOL)prepareToRecord 准备录音,主要用于创建缓冲区,如果不手动调用,在调用record录音时也会自动调用
- (BOOL)record 开始录音
- (BOOL)recordAtTime:(NSTimeInterval)time; 在指定的时间开始录音,一般用于录音暂停再恢复录音
- (BOOL)recordForDuration:(NSTimeInterval) duration; 按指定的时长开始录音
- (BOOL)recordAtTime:(NSTimeInterval)time forDuration:(NSTimeInterval) duration; 在指定的时间开始录音,并指定录音时长
- (void)pause; 暂停录音
- (void)stop; 停止录音
- (BOOL)deleteRecording; 删除录音,注意要删除录音此时录音机必须处于停止状态
- (void)updateMeters; 更新测量数据,注意只有meteringEnabled为YES此方法才可用
- (float)peakPowerForChannel:(NSUInteger)channelNumber; 指定通道的测量峰值,注意只有调用完updateMeters才有值
- (float)averagePowerForChannel:(NSUInteger)channelNumber; 指定通道的测量平均值,注意只有调用完updateMeters才有值
代理方法 说明
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag; 完成录音
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error; 录音编码发生错误
// //ViewController.m //录音 // //Created by wwh on 17/2/21. //Copyright ? 2017年 wwh. All rights reserved. //#import "ViewController.h" #import #import "MBProgressHUD.h"#define kRecordAudioFile @"Record.caf"@interface ViewController ()@property (nonatomic,strong) AVAudioRecorder *audioRecorder; //音频录音机 @property (nonatomic,strong) AVAudioPlayer *audioPlayer; //音频播放器,用于播放录音文件 @property (nonatomic,strong) NSTimer *timer; //录音声波监控 @property (nonatomic,strong) NSTimer *timer1; //播放声波监控 @property (weak, nonatomic) IBOutlet UIProgressView*audioPower; //音频波动 @end@implementation ViewController#pragma mark - 控制器视图方法- (void)dealloc { [self.timer invalidate]; self.timer = nil; [self.timer1 invalidate]; self.timer1 = nil; }- (void)viewDidLoad { [super viewDidLoad]; // 设置控制器View背景 self.view.backgroundColor = [UIColor darkGrayColor]; // 设置音频会话 [self setAudioSession]; }#pragma mark - 私有方法 /** *设置音频会话 */ - (void)setAudioSession { AVAudioSession *audioSession = [AVAudioSession sharedInstance]; //设置为播放和录音状态,以便可以在录制完之后播放录音 [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil]; [audioSession setActive:YES error:nil]; }/** *取得录音文件保存路径 * *@return 录音文件路径 */ - (NSURL *)getSavePath { NSString *urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; urlStr = [urlStr stringByAppendingPathComponent:kRecordAudioFile]; NSURL *url = [NSURL fileURLWithPath:urlStr]; return url; }/** *取得录音文件设置 *Note:在创建录音机时除了指定路径外还必须指定录音设置信息,因为录音机必须知道录音文件的格式、采样率、通道数、每个采样点的位数等信息,但是也并不是所有的信息都必须设置,通常只需要几个常用设置 * *@return 录音设置 */ - (NSDictionary *)getAudioSetting{ NSMutableDictionary *dicSettings = [NSMutableDictionary dictionary]; //设置录音格式 [dicSettings setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey]; //设置录音采样率,8000是电话采样率,对于一般录音已经够了 [dicSettings setObject:@(8000) forKey:AVSampleRateKey]; //设置通道,这里采用单声道 [dicSettings setObject:@(1) forKey:AVNumberOfChannelsKey]; //每个采样点位数,分为8、16、24、32 [dicSettings setObject:@(8) forKey:AVLinearPCMBitDepthKey]; //是否使用浮点数采样 [dicSettings setObject:@(YES) forKey:AVLinearPCMIsFloatKey]; //....其他设置等 return dicSettings; }/** *获得AVAudioRecorder对象 * *@return AVAudioRecorder对象 */ - (AVAudioRecorder *)audioRecorder{ if (!_audioRecorder) { //创建录音文件保存路径 NSURL *url = [self getSavePath]; //创建录音格式设置 NSDictionary *setting = [self getAudioSetting]; //创建录音机 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; } } 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.delegate = self; _audioPlayer.meteringEnabled = YES; [_audioPlayer prepareToPlay]; if (error) { NSLog(@"创建播放器过程中发生错误,错误信息:%@",error.localizedDescription); return nil; } } return _audioPlayer; }/** *录音声波监控定制器 * *@return 定时器 */ - (NSTimer *)timer{ if (!_timer) { _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES]; } return _timer; }/** *播放声波监控定制器 * *@return 定时器 */ - (NSTimer *)timer1{ if (!_timer1) { _timer1 = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(playAudioPowerChange) userInfo:nil repeats:YES]; } return _timer1; }/** *录音声波状态设置 */ - (void)audioPowerChange { [self.audioRecorder updateMeters]; //更新测量值 float power = [self.audioRecorder averagePowerForChannel:0]; //取得第一个通道的音频,注意音频强度范围时-160到0 CGFloat progress = (1.0/160.0)*(power+160.0); [self.audioPower setProgress:progress]; }#pragma mark - UI事件 /** *点击录音按钮 * *@param sender 录音按钮 */ - (IBAction)recordClick:(UIBarButtonItem *)sender { if (![self.audioRecorder isRecording]) { // 满足一些特定时长录音需求 //- (BOOL)recordForDuration:(NSTimeInterval) duration; [self.audioRecorder record]; //首次使用应用时如果调用record方法会询问用户是否允许使用麦克风 self.timer.fireDate = [NSDate distantPast]; } }/** *点击暂定按钮 * *@param sender 暂停按钮 */ - (IBAction)pauseClick:(UIBarButtonItem *)sender { if ([self.audioRecorder isRecording]) { [self.audioRecorder pause]; self.timer.fireDate = [NSDate distantFuture]; } }/** *点击恢复按钮 *恢复录音只需要再次调用record,AVAudioSession会帮助你记录上次录音位置并追加录音 * *@param sender 恢复按钮 */ - (IBAction)resumeClick:(UIBarButtonItem *)sender {[self recordClick:sender]; }/** *点击停止按钮 * *@param sender 停止按钮 */ - (IBAction)stopClick:(UIBarButtonItem *)sender { [self.audioRecorder stop]; self.timer.fireDate = [NSDate distantFuture]; self.audioPower.progress = 0.0; }/** *点击播放按钮 * *@param sender 播放按钮 */ - (IBAction)playClick:(UIBarButtonItem *)sender { if (![self.audioPlayer isPlaying]) { [self.audioPlayer play]; self.timer1.fireDate = [NSDate distantPast]; } }/** *播放声波状态设置 */ - (void)playAudioPowerChange { [self.audioPlayer updateMeters]; //更新测量值//取得第一个通道的音频,注意音频强度范围时-160到0 float power = [self.audioPlayer averagePowerForChannel:0]; CGFloat progress = (1.0/160.0)*(power+160.0); [self.audioPower setProgress:progress]; }#pragma mark - AVAudioRecorderDelegate Methods /** *录音完成 * *@param recorder AVAudioRecorder对象 *@param flag是否成功 */ - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{ if (flag) { [MBProgressHUD showHUDAddedTo:self.view animated:YES]; MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view]; hud.mode = MBProgressHUDModeCustomView; hud.label.text = @"录音完毕"; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [hud hideAnimated:YES]; }); } }#pragma mark - AVAudioPlayerDelegate Methods /** *播放完成 * *@param player AVAudioPlayer对象 *@param flag是否成功 */ - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag { if (flag) { [MBProgressHUD showHUDAddedTo:self.view animated:YES]; MBProgressHUD *hud = [MBProgressHUD HUDForView:self.view]; hud.mode = MBProgressHUDModeCustomView; hud.label.text = @"播放完毕"; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [hud hideAnimated:YES]; }); } }@end

    推荐阅读