Part 2 :语音录音机
其实网上很多录音的文章,这里主要说明的是网络传输音频相关的内容.
基本流程就是录音结束后获取一个wav
格式的录音,转换为amr
格式文件,转成NSData
格式,用于传输.
amr
格式的文件大小是wav
格式文件大小的十分之一左右,更适合传输.
- 先创建两个音频文件到沙盒的Tmp文件夹中(Tmp存储临时数据,iCloud 不会备份这些文件)
//创建缓存录音文件到Tmp
NSString *wavRecordFilePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"WAVtemporaryRadio.wav"];
NSString *amrRecordFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"AMRtemporaryRadio.amr"];
if (![[NSFileManager defaultManager]fileExistsAtPath:wavRecordFilePath]) {
[[NSData data] writeToFile:wavRecordFilePath atomically:YES];
}
if (![[NSFileManager defaultManager]fileExistsAtPath:amrRecordFilePath]) {
[[NSData data] writeToFile:amrRecordFilePath atomically:YES];
}
WAVtemporaryRadio.wav
文件是录音后的临时存储文件
AMRtemporaryRadio.amr
文件是用于网络传输的文件
- 懒加载
AVAudioRecorder
- (AVAudioRecorder *)audioRecorder
{
if (!_audioRecorder) {
//暂存录音文件路径
NSString *wavRecordFilePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"WAVtemporaryRadio.wav"];
NSDictionary *recordSetting = @{ AVSampleRateKey : @8000.0, // 采样率
AVFormatIDKey : @(kAudioFormatLinearPCM), // 音频格式
AVLinearPCMBitDepthKey : @16, // 采样位数 默认 16
AVNumberOfChannelsKey : @1 // 通道的数目
};
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:wavRecordFilePath] settings:recordSetting error:nil];
_audioRecorder.delegate = self;
_audioRecorder.meteringEnabled = YES;
}
return _audioRecorder;
}
- 开始录音
[self.audioRecorder prepareToRecord];
[self.audioRecorder record];
- 开启音频值测量
double lowPassResults = pow(10, (0.05 * [_self->_audioRecorder peakPowerForChannel:0]));
- 完成录音后,会进入到
AVAudioRecorder
的代理方法中,(wave_file_to_amr_file
类demo中会有)
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
//暂存录音文件路径
NSString *wavRecordFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WAVtemporaryRadio.wav"];
NSString *amrRecordFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"AMRtemporaryRadio.amr"];
//重点:把wav录音文件转换成amr文件,用于网络传输.amr文件大小是wav文件的十分之一左右
wave_file_to_amr_file([wavRecordFilePath cStringUsingEncoding:NSUTF8StringEncoding],[amrRecordFilePath cStringUsingEncoding:NSUTF8StringEncoding], 1, 16);
//返回amr音频文件Data,用于传输或存储
NSData *cacheAudioData = [NSData dataWithContentsOfFile:amrRecordFilePath];
if ([self.delegate respondsToSelector:@selector(audioRecorderDidFinishRecordingWithData:)]) {
[self.delegate audioRecorderDidFinishRecordingWithData:cacheAudioData];
}
}
Demo 地址 :https://github.com/XL-Andrew/ChatToolBarAudioButton