视频开发iOS Developer

iOS 仿微信发送语音消息按钮 - 语音录音机(二)

2017-07-19  本文已影响831人  我就叫Tom怎么了

Part 2 :语音录音机

其实网上很多录音的文章,这里主要说明的是网络传输音频相关的内容.

基本流程就是录音结束后获取一个wav格式的录音,转换为amr格式文件,转成NSData格式,用于传输.

amr格式的文件大小是wav格式文件大小的十分之一左右,更适合传输.

//创建缓存录音文件到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 *)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]));
- (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

上一篇 下一篇

猜你喜欢

热点阅读