如果你想要在iOS设备上录制音频,确保你已经将 CoreAudio.framework 库添加到目标文件中。使用 AV 库中的AVAudioRecorder 类:
NSError*error=nil;
NSString *pathAsString=[self audioRecordingPath];
NSURL *audioRecordingURL=[NSURLfileURLWithPath:pathAsString];
self.audioRecorder=[[AVAudioRecorder alloc]initWithURL:audioRecordingURLsettings:[self audioRecordingSettings] error:&error];
V框架中的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
我们将从在简单的视图控制器的头文件中声明一下需要的属性开始:
#import <UIKit/UIKit.h>
#import <CoreAudio/CoreAudioTypes.h>
#import <AVFoundation/AVFoundation.h>
@interfaceRecording_AudioViewController:UIViewController<AVAudioPlayerDelegate,AVAudioRecorderDelegate>
@property(nonatomic,strong)AVAudioRecorder*audioRecorder;
@property(nonatomic,strong)AVAudioPlayer*audioPlayer;
- (NSString*)audioRecordingPath;
- (NSDictionary*)audioRecordingSettings;
@end
当视图控制器中的视图第一次加载时,我们尝试开始录音然后如果成功的话在 5 秒后停止。
-(void)viewDidLoad
{
[super viewDidLoad];
NSError *error=nil;
NSString *pathAsString=[self audioRecordingPath];
NSURL *audioRecordingURL=[NSURLfileURLWithPath:pathAsString];
self.audioRecorder=[[AVAudioRecorder alloc]initWithURL:audioRecordingURL
settings:[self audioRecordingSettings]error:&error];
if (self.audioRecorder!=nil)
{ self.audioRecorder.delegate=self;
/* 准备开始记录 */
if([self.audioRecorder prepareToRecord] &&[self.audioRecorder record])
{
NSLog(@"Successfully started to record.");
/* 5秒之后我们停止记录 */
[selfperformSelector:@selector(stopRecordingOnAudioRecorder:)withObject:self.audioRecorder
afterDelay:5.0f];
} else {
NSLog(@"Failed to record.");
self.audioRecorder=nil;
}
} else {
NSLog(@"Failed to create an instance of the audio recorder.");
}
}
在我们的视图控制器的 viewDidLoad 方法中,我们尝试实例化一个 AVAudioRecorder类 型的对象。而且我们把这个对象赋值给了我们在同一个视图控制器的.h 文件中声明的一个属性 ,我们用一个 audioRecordingPath 方法来决定我们存储录制的文件的 URL 的 NSString 类型的路径。这个方法这样实现
-(NSString*)audioRecordingPath{
NSString *result=nil;
NSArray *folders=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsFolder=[foldersobjectAtIndex:0];
result=[documentsFolderstringByAppendingPathComponent:@"Recording.m4a"];
returnresult;
}
这个方法的返回值是程序的文档目录后面加上目标文件名。例如你程序的文档路径是:
/var/mobile/Applications/ApplicationID/Documents/
目标音频文件的目录就是:
/var/mobile/Applications/ApplicationID/Documents/Recording.m4a
我们使用了一个 dictionary 作为音频录制器的初始化方法中的 setting参数。这个dictionary 用 audioRecordingSettings 方法创建。实现如下:
-(NSDictionary*)audioRecordingSettings{
NSDictionary*result=nil;
NSMutableDictionary*settings=[[NSMutableDictionary alloc]init];[settings
setValue:[NSNumbernumberWithInteger:kAudioFormatAppleLossless]forKey:AVFormatIDKey];
[settings
setValue:[NSNumbernumberWithFloat:44100.0f]forKey:AVSampleRateKey];
[settings
setValue:[NSNumbernumberWithInteger:1]forKey:AVNumberOfChannelsKey];
[settings
setValue:[NSNumbernumberWithInteger:AVAudioQualityLow]forKey:AVEncoderAudioQualityKey];
result = [NSDictionarydictionaryWithDictionary:settings];
return result;
}
可以看到在 view controller 的 viewDidLoad 方法中成功录音 5 秒后,我们调用了stopRecordingOnAudioRecorder方法,实现如下:
-(void)stopRecordingOnAudioRecorder:(AVAudioRecorder*)paramRecorder{
//停止音频的记录
[paramRecorder stop];
}
既然我们已经停止了录制,我们要等待 delegate 消息通知我们录制确实停止了。最好不要认为是 AVAudioRecorder 的停止方法迅速终止了录制。相反的,我建议你在audioRecorderDidFinishRecording:successfully: delegate方法(在AVAudioRecorderDelegate 协议中声明的)后再继续操作。
当录制停止后,我们就可以播放录制的音频:
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder*)recordersuccessfully:(BOOL)flag{
if (flag){
NSLog(@"Successfully stopped the audio recording process.");
NSError*playbackError=nil;
NSError *readingError=nil;
NSData *fileData=
[NSDatadataWithContentsOfFile:[self audioRecordingPath]options:NSDataReadingMapped
error:&readingError];
self.audioPlayer=[[AVAudioPlayer alloc]initWithData:fileDataerror:&playbackError];
if (self.audioPlayer!=nil){
self.audioPlayer.delegate=self;
//准备开始播放
if ([self.audioPlayer prepareToPlay] &&[self.audioPlayer play])
{
NSLog(@"Started playing the recorded audio.");
} else {
NSLog(@"Could not play the audio.");
}
} else {
NSLog(@"Failed to create an audio player.");
}
} else {
NSLog(@"Stopping the audio recording failed.");
}
self.audioRecorder=nil;
}
在音频播放器播放完(如果成功的话)一首歌曲后,在音频播放器的 delegate 对中audioPlayerDidFinishPlaying:successfully: delegate方法会被调用。该方法(在AVAudioPlayerDelegate协议中声明)实现如下:
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)playersuccessfully:(BOOL)flag{
if (flag){
NSLog(@"Audio player stopped correctly.");
} else {
NSLog(@"Audio player did not stop correctly.");
}
if ([playerisEqual:self.audioPlayer])
{ self.audioPlayer=nil;
} else {
}
}