录制音频

想要在ios设备上录制音频,可以使用AVAudioRecorder类,确保你已经将CoreAudio.framework 库添加到目标文件中

AV框架中的AVAudioRecorder类使得在iOS中录制音频变得很简单。开始录制音频需要提供一些参数给AVAudioRecorder实例的initWithURL:settings:error:方法: 

保存录音文件的URL 

文件的URL是一个本地URL.AV框架会根据URL的扩展名来决定录制文件的音频格式。所以要仔细选择扩展名。 

在采样之前和过程中使用的settings 

包括采样率、频道以及其他音频录制器开始录音的信息。Setting是一个dictionary对象。 

初始化错误发生时保存到error 变量中。 

你可以在出现异常的情况下得到这个实例中的值。 

initWithURL:settings:error: 方法的setting参数很有意思。很多值都可以保存在这个setting字典里,但是在本节中我们只讨论一些最重要的: 

AVFormatIDKey 

录音的格式。可能的值有: 

• kAudioFormatLinearPCM 

• kAudioFormatAppleLossless 

AVSampleRateKey 

录制音频的采样率。 

AVNumberOfChannelsKey 

录制音频的频道编号。 

AVEncoderAudioQualityKey 

录制音频的质量,可能的值有: 

AVAudioQualityMin 

• AVAudioQualityLow 

• AVAudioQualityMedium 

• AVAudioQualityHigh 

• AVAudioQualityMax 

掌握了所有这些信息后,我们可以开始写一个可以录制音频文件然后用AVAudioPlayer播放的程序。我们要做的具体事情是: 

1. 用 Apple Lossless 格式录制音频。 

2. 把录制的音频文件用Recording.m4a文件名保存到程序的Documents目录中。 

3. 在录音开始10秒后停止录制并且立刻开始播放录制的音频。 

代码:

头文件:

[objc]  view plain copy
  1. #import <UIKit/UIKit.h>  
  2. #import <CoreAudio/CoreAudioTypes.h>  
  3. #import <AVFoundation/AVFoundation.h>  
  4.   
  5. @interface ViewController : UIViewController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>  
  6. @property(nonatomicstrong)AVAudioRecorder *audioRecorder;  
  7. @property(nonatomicstrong)AVAudioPlayer *audioPlayer;  
  8. -(NSString *)audioRecordingPath;  
  9. -(NSString *)audioRecordingSettings;  
  10. @end  

实现文件:

[objc]  view plain copy
  1. //  
  2. //  ViewController.m  
  3. //  录制音频  
  4. //  
  5. //  Created by Rio.King on 13-11-2.  
  6. //  Copyright (c) 2013年 Rio.King. All rights reserved.  
  7. //  
  8.   
  9. #import "ViewController.h"  
  10.   
  11. @interface ViewController ()  
  12.   
  13. @end  
  14.   
  15. @implementation ViewController  
  16.   
  17. - (void)viewDidLoad  
  18. {  
  19.     [super viewDidLoad];  
  20.       
  21.     NSError *error = nil;  
  22.     NSString *pathAsString = [self audioRecordingPath];  
  23.     NSURL *audioRecordingURL = [NSURL fileURLWithPath:pathAsString];  
  24.     self.audioRecorder = [[AVAudioRecorder alloc] initWithURL:audioRecordingURL settings:[self audioRecordingSettings] error:&error];  
  25.     if (self.audioRecorder != nil) {  
  26.         self.audioRecorder.delegate = self;  
  27.         /*prepare the recorder and then start the recording*/  
  28.         if ([self.audioRecorder prepareToRecord] && [self.audioRecorder record]) {  
  29.             NSLog(@"Successfully started to record.");  
  30.             /*after five seconds, let's stop the recording process*/  
  31.             [self performSelector:@selector(stopRecordingOnAudioRecorder:) withObject:self.audioRecorder afterDelay:10.0f];  
  32.         }else{  
  33.             NSLog(@"Failed to record.");  
  34.             self.audioRecorder = nil;  
  35.         }  
  36.     }else{  
  37.         NSLog(@"failed to create an instance of the audio recorder.");  
  38.     }  
  39. }  
  40.   
  41. -(NSString *)audioRecordingPath{  
  42.     NSString *result = nil;  
  43.     NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  44.     NSString *documentsFolder = [folders objectAtIndex:0];  
  45.     result = [documentsFolder stringByAppendingPathComponent:@"Recording.m4a"];  
  46.     return result;  
  47. }  
  48.   
  49. - (NSDictionary *) audioRecordingSettings{  
  50.     NSDictionary *result = nil;  
  51.     /* Let's prepare the audio recorder options in the dictionary. 
  52.      Later we will use this dictionary to instantiate an audio 
  53.      recorder of type AVAudioRecorder */  
  54.     NSMutableDictionary *settings = [[NSMutableDictionary alloc] init];  
  55.     [settings  
  56.      setValue:[NSNumber numberWithInteger:kAudioFormatAppleLossless]  
  57.      forKey:AVFormatIDKey];  
  58.     [settings  
  59.      setValue:[NSNumber numberWithFloat:44100.0f]  
  60.      forKey:AVSampleRateKey];  
  61.     [settings  
  62.      setValue:[NSNumber numberWithInteger:1]  
  63.      forKey:AVNumberOfChannelsKey];  
  64.     [settings  
  65.      setValue:[NSNumber numberWithInteger:AVAudioQualityLow]  
  66.      forKey:AVEncoderAudioQualityKey];  
  67.     result = [NSDictionary dictionaryWithDictionary:settings];  
  68.     return result;  
  69. }  
  70.   
  71.   
  72. - (void) stopRecordingOnAudioRecorder:(AVAudioRecorder *)paramRecorder{  
  73.     /* Just stop the audio recorder here */  
  74.     [paramRecorder stop];  
  75. }  
  76.   
  77.   
  78. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder  
  79.                            successfully:(BOOL)flag{  
  80.     if (flag){  
  81.         NSLog(@"Successfully stopped the audio recording process.");  
  82.         /* Let's try to retrieve the data for the recorded file */  
  83.         NSError *playbackError = nil;  
  84.         NSError *readingError = nil;  
  85.         NSData *fileData =  
  86.         [NSData dataWithContentsOfFile:[self audioRecordingPath]  
  87.                                options:NSDataReadingMapped  
  88.                                  error:&readingError];  
  89.         /* Form an audio player and make it play the recorded data */  
  90.         self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData  
  91.                                                          error:&playbackError];  
  92.         /* Could we instantiate the audio player? */  
  93.         if (self.audioPlayer != nil){  
  94.             self.audioPlayer.delegate = self;  
  95.             /* Prepare to play and start playing */  
  96.             if ([self.audioPlayer prepareToPlay] &&  
  97.                 [self.audioPlayer play]){  
  98.                 NSLog(@"Started playing the recorded audio.");  
  99.             } else {  
  100.                 NSLog(@"Could not play the audio.");  
  101.             }  
  102.         } else {  
  103.             NSLog(@"Failed to create an audio player.");  
  104.         }  
  105.     } else {  
  106.         NSLog(@"Stopping the audio recording failed.");  
  107.     }  
  108.     /* Here we don't need the audio recorder anymore */  
  109.     self.audioRecorder = nil;  
  110. }  
  111.   
  112. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player  
  113.                        successfully:(BOOL)flag{  
  114.     if (flag){  
  115.         NSLog(@"Audio player stopped correctly.");  
  116.     } else {  
  117.         NSLog(@"Audio player did not stop correctly.");  
  118.     }  
  119.     if ([player isEqual:self.audioPlayer]){  
  120.         self.audioPlayer = nil;  
  121.     } else {  
  122.         /* This is not the player */  
  123.     }  
  124. }  
  125.   
  126.   
  127. - (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{  
  128.     /* The audio session has been deactivated here */  
  129. }  
  130. - (void)audioPlayerEndInterruption:(AVAudioPlayer *)player  
  131.                          withFlags:(NSUInteger)flags{  
  132.     if (flags == AVAudioSessionInterruptionFlags_ShouldResume){  
  133.         [player play];  
  134.     }  
  135. }  
  136.   
  137.   
  138.   
  139. #pragma mark -处理音频录制过程中的中断  
  140. - (void)audioRecorderBeginInterruption:(AVAudioRecorder *)recorder{  
  141.     NSLog(@"Recording process is interrupted");  
  142. }  
  143. - (void)audioRecorderEndInterruption:(AVAudioRecorder *)recorder  
  144.                            withFlags:(NSUInteger)flags{  
  145.     if (flags == AVAudioSessionInterruptionFlags_ShouldResume){  
  146.         NSLog(@"Resuming the recording...");  
  147.         [recorder record];  
  148.     }  
  149. }  
  150.   
  151.   
  152.   
  153.   
  154. - (void)didReceiveMemoryWarning  
  155. {  
  156.     [super didReceiveMemoryWarning];  
  157.     // Dispose of any resources that can be recreated.  
  158. }  
  159.   
  160. @end  

运行结果:

2013-11-02 21:01:52.144 录制音频[1786:a0b] Successfully started to record.

2013-11-02 21:02:02.146 录制音频[1786:a0b] Successfully stopped the audio recording process.

2013-11-02 21:02:02.160 录制音频[1786:a0b] Started playing the recorded audio.

2013-11-02 21:02:12.128 录制音频[1786:a0b] Audio player stopped correctly.


原文链接:http://blog.csdn.net/chaoyuan899/article/details/14075697

你可能感兴趣的:(录制音频)