录音属于AVFAudio里面的一个高级封装。在实际运用中,可以使用到语音录制,比如聊天等。这个对语音录制做一个简单的了解。
1.基础配置
/*
音频基础
声波是一种机械波,是一种模拟信号。
PCM,全称脉冲编码调制,是一种模拟信号的数字化的方法。
采样精度(bit pre sample),每个声音样本的采样位数。
采样频率(sample rate)每秒钟采集多少个声音样本。
声道(channel):相互独立的音频信号数,单声道(mono)立体声(Stereo)
语音帧(frame),In audio data a frame is one sample across all channels.
*/
// 语音录制
// 格式(真机)
NSMutableDictionary *recordSetting = [NSMutableDictionary dictionary];
NSError *error = nil;
NSString *outputPath = nil;
// 输出地址
#if TARGET_IPHONE_SIMULATOR//模拟器
outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.caf"];
// 设置录音格式
[recordSetting setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
#elif TARGET_OS_IPHONE//真机
NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.m4a"];
[recordSetting setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
#endif
// 设置录音采样率
[recordSetting setObject:@(8000) forKey:AVSampleRateKey];
// 设置通道,这里采用单声道 1:单声道;2:立体声
[recordSetting setObject:@(1) forKey:AVNumberOfChannelsKey];
// 每个采样点位数,分为8、16、24、32
[recordSetting setObject:@(8) forKey:AVLinearPCMBitDepthKey];
// 大端还是小端,是内存的组织方式
[recordSetting setObject:@(NO) forKey:AVLinearPCMIsBigEndianKey];
// 是否使用浮点数采样
[recordSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
// 是否交叉
[recordSetting setObject:@(NO) forKey:AVLinearPCMIsNonInterleaved];
// 设置录音质量
[recordSetting setObject:@(AVAudioQualityMin) forKey:AVEncoderAudioQualityKey];
// 比特率
[recordSetting setObject:@(128000) forKey:AVEncoderBitRateKey];
// 每个声道音频比特率
[recordSetting setObject:@(128000) forKey:AVEncoderBitRatePerChannelKey];
// 深度
[recordSetting setObject:@(8) forKey:AVEncoderBitDepthHintKey];
// 设置录音采样质量
[recordSetting setObject:@(AVAudioQualityMin) forKey:AVSampleRateConverterAudioQualityKey];
// 策略 AVSampleRateConverterAlgorithmKey
// 采集率算法 AVSampleRateConverterAlgorithmKey
// 渠道布局 AVChannelLayoutKey
2.录音类初始化
// 初始化
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:outputPath] settings:recordSetting error:&error];
// 设置协议
recorder.delegate = self;
// 准备录制
[recorder prepareToRecord];
3.录音
[recorder record];
4.暂停
[recorder pause];
5.停止
[recorder stop];
6.协议
// 录音结束
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
NSLog(@"%@", recorder.url);
}
// 发生错误调用
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
NSLog(@"%@", error);
}