iOS仿发送语⾳消息按钮-语⾳录⾳机(⼆)#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;
_ingEnabled = 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
//返回amr⾳频⽂件Data,⽤于传输或存储
NSData *cacheAudioData = [NSData dataWithContentsOfFile:amrRecordFilePath];
if ([self.delegate respondsToSelector:@selector(audioRecorderDidFinishRecordingWithData:)]) {
[self.delegate audioRecorderDidFinishRecordingWithData:cacheAudioData];
}
}
复制代码
Demo 地址 :

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。