錄音屬于AVFAudio里面的一個(gè)高級(jí)封裝。在實(shí)際運(yùn)用中,可以使用到語音錄制,比如聊天等。這個(gè)對(duì)語音錄制做一個(gè)簡(jiǎn)單的了解。
1.基礎(chǔ)配置
/*
音頻基礎(chǔ)
聲波是一種機(jī)械波,是一種模擬信號(hào)。
PCM,全稱脈沖編碼調(diào)制,是一種模擬信號(hào)的數(shù)字化的方法。
采樣精度(bit pre sample),每個(gè)聲音樣本的采樣位數(shù)。
采樣頻率(sample rate)每秒鐘采集多少個(gè)聲音樣本。
聲道(channel):相互獨(dú)立的音頻信號(hào)數(shù),單聲道(mono)立體聲(Stereo)
語音幀(frame),In audio data a frame is one sample across all channels.
*/
// 語音錄制
// 格式(真機(jī))
NSMutableDictionary *recordSetting = [NSMutableDictionary dictionary];
NSError *error = nil;
NSString *outputPath = nil;
// 輸出地址
#if TARGET_IPHONE_SIMULATOR//模擬器
outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.caf"];
// 設(shè)置錄音格式
[recordSetting setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
#elif TARGET_OS_IPHONE//真機(jī)
NSString *outputPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"1.m4a"];
[recordSetting setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
#endif
// 設(shè)置錄音采樣率
[recordSetting setObject:@(8000) forKey:AVSampleRateKey];
// 設(shè)置通道,這里采用單聲道 1:單聲道;2:立體聲
[recordSetting setObject:@(1) forKey:AVNumberOfChannelsKey];
// 每個(gè)采樣點(diǎn)位數(shù),分為8、16、24、32
[recordSetting setObject:@(8) forKey:AVLinearPCMBitDepthKey];
// 大端還是小端,是內(nèi)存的組織方式
[recordSetting setObject:@(NO) forKey:AVLinearPCMIsBigEndianKey];
// 是否使用浮點(diǎn)數(shù)采樣
[recordSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
// 是否交叉
[recordSetting setObject:@(NO) forKey:AVLinearPCMIsNonInterleaved];
// 設(shè)置錄音質(zhì)量
[recordSetting setObject:@(AVAudioQualityMin) forKey:AVEncoderAudioQualityKey];
// 比特率
[recordSetting setObject:@(128000) forKey:AVEncoderBitRateKey];
// 每個(gè)聲道音頻比特率
[recordSetting setObject:@(128000) forKey:AVEncoderBitRatePerChannelKey];
// 深度
[recordSetting setObject:@(8) forKey:AVEncoderBitDepthHintKey];
// 設(shè)置錄音采樣質(zhì)量
[recordSetting setObject:@(AVAudioQualityMin) forKey:AVSampleRateConverterAudioQualityKey];
// 策略 AVSampleRateConverterAlgorithmKey
// 采集率算法 AVSampleRateConverterAlgorithmKey
// 渠道布局 AVChannelLayoutKey
2.錄音類初始化
// 初始化
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:outputPath] settings:recordSetting error:&error];
// 設(shè)置協(xié)議
recorder.delegate = self;
// 準(zhǔn)備錄制
[recorder prepareToRecord];
3.錄音
[recorder record];
4.暫停
[recorder pause];
5.停止
[recorder stop];
6.協(xié)議
// 錄音結(jié)束
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
NSLog(@"%@", recorder.url);
}
// 發(fā)生錯(cuò)誤調(diào)用
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error {
NSLog(@"%@", error);
}