iOS 录音

录音和播放音乐使用的是同一个框架,都是iOS系统提供的AVFoundation.framwork

首先,还是创建项目  

起名:TestAVFoundationRecorder


接下来 导入AVFoundation.framwork

具体操作参照上一节

完成后项目目录如下

打开项目默认生成ViewController.m 添加代码

导入头文件

[objc]  view plain  copy
  1. #import <AVFoundation/AVFoundation.h>  

创建变量

[objc]  view plain  copy
  1. @property (nonatomic,strongAVAudioRecorder *audioRecorder;//音频录音机  
  2. @property (nonatomic,strongAVAudioPlayer *audioPlayer;//音频播放器,用于播放录音文件  
  3. @property (nonatomic,strongNSTimer *timer;//录音声波监控(注意这里暂时不对播放进行监控)  
  4.   
  5. @property (strongnonatomicUIButton *record;//开始录音  
  6. @property (strongnonatomicUIButton *pause;//暂停录音  
  7. @property (strongnonatomicUIButton *resume;//恢复录音  
  8. @property (strongnonatomicUIButton *stop;//停止录音  
  9. @property (strongnonatomicUIProgressView *audioPower;//音频波动  


初始化界面

[objc]  view plain  copy
  1. - (void)viewDidLoad {  
  2.     [super viewDidLoad];  
  3.     // Do any additional setup after loading the view, typically from a nib.  
  4.       
  5.     _record=[[UIButton alloc]initWithFrame:CGRectMake(103006036)];  
  6.     [_record setTitle:@"录音" forState:UIControlStateNormal];  
  7.     [_record setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  
  8.     [_record addTarget:self action:@selector(recordClick:) forControlEvents:UIControlEventTouchUpInside];  
  9.     [self.view addSubview:_record];  
  10.       
  11.     _pause=[[UIButton alloc]initWithFrame:CGRectMake(803006036)];  
  12.     [_pause setTitle:@"暂停" forState:UIControlStateNormal];  
  13.     [_pause setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  
  14.     [_pause addTarget:self action:@selector(pauseClick:) forControlEvents:UIControlEventTouchUpInside];  
  15.     [self.view addSubview:_pause];  
  16.       
  17.     _resume=[[UIButton alloc]initWithFrame:CGRectMake(1503006036)];  
  18.     [_resume setTitle:@"恢复" forState:UIControlStateNormal];  
  19.     [_resume setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  
  20.     [_resume addTarget:self action:@selector(resumeClick:) forControlEvents:UIControlEventTouchUpInside];  
  21.     [self.view addSubview:_resume];  
  22.       
  23.     _stop=[[UIButton alloc]initWithFrame:CGRectMake(2203006036)];  
  24.     [_stop setTitle:@"停止" forState:UIControlStateNormal];  
  25.     [_stop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];  
  26.     [_stop addTarget:self action:@selector(stopClick:) forControlEvents:UIControlEventTouchUpInside];  
  27.     [self.view addSubview:_stop];  
  28.       
  29.       
  30.     _audioPower= [[UIProgressView alloc] initWithProgressViewStyle: UIProgressViewStyleDefault];  
  31.     _audioPower.frame=CGRectMake(0100self.view.bounds.size.width36);  
  32.     [self.view addSubview:_audioPower];  
  33.       
  34.     [self setAudioSession];  
  35. }  


创建一个常量作为录音文件的名称

[objc]  view plain  copy
  1. #define kRecordAudioFile @"myRecord.caf"  


最后我们实现一下 个个按钮点击之后的动作  以及录音等等 

[objc]  view plain  copy
  1. #pragma mark - 私有方法  
  2. /** 
  3.  *  设置音频会话 
  4.  */  
  5. -(void)setAudioSession{  
  6.     AVAudioSession *audioSession=[AVAudioSession sharedInstance];  
  7.     //设置为播放和录音状态,以便可以在录制完之后播放录音  
  8.     [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];  
  9.     [audioSession setActive:YES error:nil];  
  10. }  
  11.   
  12. /** 
  13.  *  取得录音文件保存路径 
  14.  * 
  15.  *  @return 录音文件路径 
  16.  */  
  17. -(NSURL *)getSavePath{  
  18.     NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];  
  19.       
  20.     NSFileManager *fileManager = [NSFileManager defaultManager];  
  21.       
  22.       
  23.     if(![fileManager fileExistsAtPath:urlStr]) //如果不存在  
  24.           
  25.     {  
  26.         NSLog(@"xxx.txt is not exist");  
  27.     }else{  
  28.         NSLog(@"xxx.txt is  exist");  
  29.     }  
  30.       
  31.       
  32.     urlStr=[urlStr stringByAppendingPathComponent:kRecordAudioFile];  
  33.     NSLog(@"file path:%@",urlStr);  
  34.     NSURL *url=[NSURL fileURLWithPath:urlStr];  
  35.     return url;  
  36. }  
  37.   
  38. ///var/mobile/Applications/F0CCA9DC-FFBE-4701-8396-2E6EB9509292/Documents/myRecord.caf  
  39. ///var/mobile/Applications/F0CCA9DC-FFBE-4701-8396-2E6EB9509292/Documents/myRecord.caf  
  40. /** 
  41.  *  取得录音文件设置 
  42.  * 
  43.  *  @return 录音设置 
  44.  */  
  45. -(NSDictionary *)getAudioSetting{  
  46.     NSMutableDictionary *dicM=[NSMutableDictionary dictionary];  
  47.     //设置录音格式  
  48.     [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];  
  49.     //设置录音采样率,8000是电话采样率,对于一般录音已经够了  
  50.     [dicM setObject:@(8000) forKey:AVSampleRateKey];  
  51.     //设置通道,这里采用单声道  
  52.     [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];  
  53.     //每个采样点位数,分为8、16、24、32  
  54.     [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];  
  55.     //是否使用浮点数采样  
  56.     [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];  
  57.     //....其他设置等  
  58.     return dicM;  
  59. }  
  60.   
  61. /** 
  62.  *  获得录音机对象 
  63.  * 
  64.  *  @return 录音机对象 
  65.  */  
  66. -(AVAudioRecorder *)audioRecorder{  
  67.     if (!_audioRecorder) {  
  68.         //创建录音文件保存路径  
  69.         NSURL *url=[self getSavePath];  
  70.         //创建录音格式设置  
  71.         NSDictionary *setting=[self getAudioSetting];  
  72.         //创建录音机  
  73.         NSError *error=nil;  
  74.         _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];  
  75.         _audioRecorder.delegate=self;  
  76.         _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES  
  77.         if (error) {  
  78.             NSLog(@"创建录音机对象时发生错误,错误信息:%@",error.localizedDescription);  
  79.             return nil;  
  80.         }  
  81.     }  
  82.     return _audioRecorder;  
  83. }  
  84.   
  85. /** 
  86.  *  创建播放器 
  87.  * 
  88.  *  @return 播放器 
  89.  */  
  90. -(AVAudioPlayer *)audioPlayer{  
  91.     if (!_audioPlayer) {  
  92.         NSURL *url=[self getSavePath];  
  93.         NSError *error=nil;  
  94.         _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];  
  95.         _audioPlayer.numberOfLoops=0;  
  96.         [_audioPlayer prepareToPlay];  
  97.         if (error) {  
  98.             NSLog(@"创建播放器过程中发生错误,错误信息:%@",error.localizedDescription);  
  99.             return nil;  
  100.         }  
  101.     }  
  102.     return _audioPlayer;  
  103. }  
  104.   
  105. /** 
  106.  *  录音声波监控定制器 
  107.  * 
  108.  *  @return 定时器 
  109.  */  
  110. -(NSTimer *)timer{  
  111.     if (!_timer) {  
  112.         _timer=[NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];  
  113.     }  
  114.     return _timer;  
  115. }  
  116.   
  117. /** 
  118.  *  录音声波状态设置 
  119.  */  
  120. -(void)audioPowerChange{  
  121.     [self.audioRecorder updateMeters];//更新测量值  
  122.     float power= [self.audioRecorder averagePowerForChannel:0];//取得第一个通道的音频,注意音频强度范围时-160到0  
  123.     CGFloat progress=(1.0/160.0)*(power+160.0);  
  124.     [self.audioPower setProgress:progress];  
  125. }  
  126.   
  127. #pragma mark - UI事件  
  128. /** 
  129.  *  点击录音按钮 
  130.  * 
  131.  *  @param sender 录音按钮 
  132.  */  
  133.   
  134. - (void)recordClick:(UIButton *)sender {  
  135. //    if (![self.audioPlayer isPlaying]) {  
  136. //        [self.audioPlayer play];  
  137. //    }  
  138. //  
  139.     if (![self.audioRecorder isRecording]) {  
  140.         [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风  
  141.         self.timer.fireDate=[NSDate distantPast];  
  142.     }  
  143. }  
  144.   
  145. /** 
  146.  *  点击暂定按钮 
  147.  * 
  148.  *  @param sender 暂停按钮 
  149.  */  
  150. - (void)pauseClick:(UIButton *)sender {  
  151.     if ([self.audioRecorder isRecording]) {  
  152.         [self.audioRecorder pause];  
  153.         self.timer.fireDate=[NSDate distantFuture];  
  154.     }  
  155. }  
  156.   
  157. /** 
  158.  *  点击恢复按钮 
  159.  *  恢复录音只需要再次调用record,AVAudioSession会帮助你记录上次录音位置并追加录音 
  160.  * 
  161.  *  @param sender 恢复按钮 
  162.  */  
  163. - (void)resumeClick:(UIButton *)sender {  
  164.     [self recordClick:sender];  
  165. }  
  166.   
  167. /** 
  168.  *  点击停止按钮 
  169.  * 
  170.  *  @param sender 停止按钮 
  171.  */  
  172. - (void)stopClick:(UIButton *)sender {  
  173.     [self.audioRecorder stop];  
  174.     self.timer.fireDate=[NSDate distantFuture];  
  175.     self.audioPower.progress=0.0;  
  176. }  
  177.   
  178. #pragma mark - 录音机代理方法  
  179. /** 
  180.  *  录音完成,录音完成后播放录音 
  181.  * 
  182.  *  @param recorder 录音机对象 
  183.  *  @param flag     是否成功 
  184.  */  
  185. -(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{  
  186.     if (![self.audioPlayer isPlaying]) {  
  187.         [self.audioPlayer play];  
  188.     }  
  189.     NSLog(@"录音完成!");  
  190. }  


到此 我们基本实现了功能

运行项目看看 

点击录音 看看 是不是 可以是用来 。点击停止之后录音结束并且自动开发播放录音

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值