一、业务环境
将本地的录音文件 .caf 文件通过网络上传到服务器,服务器将此文件保存为 .mp3 格式。
二、实现思路
( 1 ) 通过使用AVAudioRecorder,将录音文件保存到本地
( 2 ) 用AFNetworking上传本地 .caf 文件到服务器
( 3 ) 注意AFNetworking的 minetype 配置和AVAudioRecorder的参数配置,要不然会出现音频失帧和上传失败。
三、具体代码实现
( 1 ) 录音工具创建
/*
* AVAudioRecorder 初始化
*/
- (AVAudioRecorder *)recorder {
if (!_recorder) {
// 1.获取沙盒地址
NSString *filePath = [path stringByAppendingPathComponent:@"ihefe_ichat.caf"];
self.recordFileUrl = [NSURL fileURLWithPath:filePath];
NSLog(@"filePath: %@", filePath);
// 2.录音参数设置
NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
//设置录音格式 AVFormatIDKey==kAudioFormatLinearPCM
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量), 采样率必须要设为11025才能使转化成mp3格式后不会失真
[recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
//录音通道数 1 或 2 ,要转换成mp3格式必须为双通道
[recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
//线性采样位数 8、16、24、32
[recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//录音的质量
[recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
// 3.创建AVAudioRecorder对象
_recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:NULL];
_recorder.delegate = self;
_recorder.meteringEnabled = YES;
[_recorder prepareToRecord];
}
return _recorder;
}
( 2 ) AFNetworking文件上传
/*
* 上传.mp3文件
*/
- (void)uploadFile
{
NSURL *mp3Url = [NSURL URLWithString:@"自己随便写个音频文件地址"];//本例子是将本地的 .caf 文件上传到服务器上面去
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"image/jpeg", nil];
NSMutableDictionary *para = [NSMutableDictionary dictionary];
para[@"action"] = @"999";
[manager POST:@"http://push.hjourney.cn/api.php?c=Index2" parameters:para constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// application/octer-stream audio/mpeg video/mp4 application/octet-stream
/* url : 本地文件路径
* name : 与服务端约定的参数
* fileName : 自己随便命名的
* mimeType : 文件格式类型 [mp3 : application/octer-stream application/octet-stream] [mp4 : video/mp4]
*/
[formData appendPartWithFileURL:mp3Url name:@"video" fileName:@"xxx.mp3" mimeType:@"application/octet-stream" error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {
float progress = 1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
NSLog(@"上传进度----- %f",progress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"上传成功 %@",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传失败 %@",error);
}];
}
Demo下载地址: Demo_RecordAndPlayVoice