前面 我们讲了 iOS下播放音效,播放音乐,这一节我们主要讲一下iOS录音功能
上一节地址:http://blog.youkuaiyun.com/lwjok2007/article/details/50425324
录音和播放音乐使用的是同一个框架,都是iOS系统提供的AVFoundation.framwork
首先,还是创建项目
起名:TestAVFoundationRecorder
接下来 导入AVFoundation.framwork
具体操作参照上一节
完成后项目目录如下
打开项目默认生成ViewController.m 添加代码
导入头文件
#import <AVFoundation/AVFoundation.h>
创建变量
@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;//音频波动
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_record=[[UIButton alloc]initWithFrame:CGRectMake(10, 300, 60, 36)];
[_record setTitle:@"录音" forState:UIControlStateNormal];
[_record setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_record addTarget:self action:@selector(recordClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_record];
_pause=[[UIButton alloc]initWithFrame:CGRectMake(80, 300, 60, 36)];
[_pause setTitle:@"暂停" forState:UIControlStateNormal];
[_pause setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_pause addTarget:self action:@selector(pauseClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_pause];
_resume=[[UIButton alloc]initWithFrame:CGRectMake(150, 300, 60, 36)];
[_resume setTitle:@"恢复" forState:UIControlStateNormal];
[_resume setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_resume addTarget:self action:@selector(resumeClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_resume];
_stop=[[UIButton alloc]initWithFrame:CGRectMake(220, 300, 60, 36)];
[_stop setTitle:@"停止" forState:UIControlStateNormal];
[_stop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_stop addTarget:self action:@selector(stopClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_stop];
_audioPower= [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];
_audioPower.frame=CGRectMake(0, 100, self.view.bounds.size.width, 36);
[self.view addSubview:_audioPower];
[self setAudioSession];
}
#define kRecordAudioFile @"myRecord.caf"
最后我们实现一下 个个按钮点击之后的动作 以及录音等等
#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];
NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:urlStr]) //如果不存在
{
NSLog(@"xxx.txt is not exist");
}else{
NSLog(@"xxx.txt is exist");
}
urlStr=[urlStr stringByAppendingPathComponent:kRecordAudioFile];
NSLog(@"file path:%@",urlStr);
NSURL *url=[NSURL fileURLWithPath:urlStr];
return url;
}
///var/mobile/Applications/F0CCA9DC-FFBE-4701-8396-2E6EB9509292/Documents/myRecord.caf
///var/mobile/Applications/F0CCA9DC-FFBE-4701-8396-2E6EB9509292/Documents/myRecord.caf
/**
* 取得录音文件设置
*
* @return 录音设置
*/
-(NSDictionary *)getAudioSetting{
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;
}
/**
* 获得录音机对象
*
* @return 录音机对象
*/
-(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 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;
}
/**
* 录音声波状态设置
*/
-(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 录音按钮
*/
- (void)recordClick:(UIButton *)sender {
// if (![self.audioPlayer isPlaying]) {
// [self.audioPlayer play];
// }
//
if (![self.audioRecorder isRecording]) {
[self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
self.timer.fireDate=[NSDate distantPast];
}
}
/**
* 点击暂定按钮
*
* @param sender 暂停按钮
*/
- (void)pauseClick:(UIButton *)sender {
if ([self.audioRecorder isRecording]) {
[self.audioRecorder pause];
self.timer.fireDate=[NSDate distantFuture];
}
}
/**
* 点击恢复按钮
* 恢复录音只需要再次调用record,AVAudioSession会帮助你记录上次录音位置并追加录音
*
* @param sender 恢复按钮
*/
- (void)resumeClick:(UIButton *)sender {
[self recordClick:sender];
}
/**
* 点击停止按钮
*
* @param sender 停止按钮
*/
- (void)stopClick:(UIButton *)sender {
[self.audioRecorder stop];
self.timer.fireDate=[NSDate distantFuture];
self.audioPower.progress=0.0;
}
#pragma mark - 录音机代理方法
/**
* 录音完成,录音完成后播放录音
*
* @param recorder 录音机对象
* @param flag 是否成功
*/
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
if (![self.audioPlayer isPlaying]) {
[self.audioPlayer play];
}
NSLog(@"录音完成!");
}
到此 我们基本实现了功能
运行项目看看
点击录音 看看 是不是 可以是用来 。点击停止之后录音结束并且自动开发播放录音
项目代码我们会上传群空间【51230AVFoundationRecorder.zip】
苹果开发群 :512298106 欢迎加入 欢迎讨论问题