录音功能研究了一周 总结的简单的录音和播放 满足录音60秒以内的上传和下载
用的AVFoundation框架中的 AVAudioRecorder 进行录音 用 AVAudioPlayer进行的播放
录音的格式选用的是AAC的,iOS , 安卓可以播放,服务器需要转成MP3播放
录音代码
AVAudioSession *session = [AVAudioSession sharedInstance];//控制整个系统
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryRecord error:&sessionError];//播放的时候用的AVAudioSessionCategoryPlayback
if (sessionError) {
NSLog(@"设置AVAudioSession大管家的时候报的错_____%@",sessionError.description);
}//判断后台有没有播放
if (session == nil) {
NSLog(@"AVAudioSession后台有播放:%@", [sessionError description]);
} else {
[session setActive:YES error:nil];
}
[self.recorder record];
准备录音配置
- (AVAudioRecorder *)recorder {
if (_recorder == nil) {
NSMutableDictionary* recordSettingAAC = [[NSMutableDictionary alloc] init];
[recordSettingAAC setValue :[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];//AAC 格式的压缩比和品质都是实用的,文件小音质高 AAC(Advanced Audio Coding),中文名:高级音频编码,出现于1997年,基于MPEG-2的音频编码技术。由Fraunhofer IIS、杜比实验室、AT&T、Sony等公司共同开发,目的是取代MP3格式。2000年,MPEG-4标准出现后,AAC重新集成了其特性,加入了SBR技术和PS技术,为了区别于传统的MPEG-2 AAC又称为MPEG-4 AAC。http://www.mamicode.com/info-detail-986202.html
[recordSettingAAC setValue:[NSNumber numberWithFloat:32000.0] forKey:AVSampleRateKey];//设置录音采样率(Hz) 如:AVSampleRateKey==8000/44100/96000(影响音频的质量), 此处采样频率设置成8000就够用,咱们打电话的采样平率就是8000 设置成32000 是因为后台转MP3时的限制
[recordSettingAAC setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];//录音通道数 1 或 2 ,要转换成mp3格式必须为双通道
[recordSettingAAC setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
// [recordSettingAAC setValue:[NSNumber numberWithInt:16] forKey:AVEncoderBitRateKey];//ios7 可以 ios9 以上设置这句话会闪退
[recordSettingAAC setObject:@(8) forKey:AVLinearPCMBitDepthKey]; //线性采样位数 8、16、24、32
[recordSettingAAC setObject:@(YES) forKey:AVLinearPCMIsFloatKey]; //是否使用浮点数采样
NSError *error;
_recorder = [[AVAudioRecorder alloc] initWithURL:self.urlRecordFile settings:recordSettingAAC error:&error];
if (error || self.recorder == nil) {
NSLog(@"录音创建时候的错误___%@",error.description);
}
_recorder.delegate = self;
_recorder.meteringEnabled = YES;
[_recorder prepareToRecord];
}
return _recorder;
}
我将录音文件 存在 tem 临时文件
- (NSURL *)urlRecordFile
{
if (_urlRecordFile == nil) {
_urlRecordFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:@TmpFile.aac"]];//注意后缀 一定要加上mac 否则上传给服务器他们不能判断文件类型导致文件播放失败
}
return _urlRecordFile;
}
录音成功后上传给服务器:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.requestSerializer.timeoutInterval = 10;
//上传文件流
[manager POST:urlString parameters:dictionary constructingBodyWithBlock:^(idformData) {
[formData appendPartWithFileData:dataVoice name:@"file" fileName:@"text.aac" mimeType:@"audio/mpeg3"];
//NSData *dataVoice = [NSData dataWithContentsOfURL: self.urlRecordFile]];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSError * error = nil;
NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
if (!error) {
} else {
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
下载:
NSData *dataAudio = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
播放:
AVAudioSession *session = [AVAudioSession sharedInstance];//控制整个系统
NSError *sessionError;
[session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
NSError *playError;
//NSData *data = [NSData dataWithContentsOfURL:self.urlRecordFile];本地的数据也可以进行播放
self.player = [[AVAudioPlayer alloc] initWithData:dataAudio error:&playError];
self.player.delegate = self;
//当播放录音为空, 打印错误信息
if (self.player == nil) {
NSLog(@"播放器的问题: %@", [playError description]);
}
[self.player play];
下面说说录音文件的大小
[recordSettingAAC setValue:[NSNumber numberWithFloat:16000.0] forKey:AVSampleRateKey];采样率是16000 苹果4s 60秒 369kb 性能好的手机相应的录音文件会大点
[recordSettingAAC setValue:[NSNumber numberWithFloat:8000.0] forKey:AVSampleRateKey];采样率是8000 的4s 60秒 250kb
采样率越大对应的录音的文件就越大,因为采样率大 就意味着采样的频率越高,采样的录音更加接近原声。32000的采样率 生成的录音文件大概是800kb 左右
类似QQ录音那样根据音量大小展示的相应的动画的代码如下:
录音的时候开启定时器:
_timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateImage) userInfo:nil repeats:YES];
[_timer fire];
- (void)updateImage {
[self.recorder updateMeters];
double lowPassResults = pow(10, (0.05 * [self.recorder peakPowerForChannel:0]));
float result = 10 * (float)lowPassResults;
NSLog(@"音量%f", result);
int no = 1;
if (result > 0 && result <= 1.5) {
no = 1;
} else if (result > 1.5 && result <= 2.5) {
no = 2;
} else if (result > 2.5 && result <= 3.5) {
no = 3;
} else if (result > 3.5 && result <= 5.0) {
no = 4;
} else if (result > 5.0 && result <= 8) {
no = 5;
} else if (result > 8 ) {
no = 6;
}
}
//根据音量的大小做相应的帧动画
self.imaViewLeft.animationDuration = 0.5;//和取声音的频率一致
self.imaViewLeft.animationImages = [self arrayImageAnimationLeftWithNum:num];//这句话是指给imageview添加动画的图片
[self.imaViewLeft startAnimating];
//图片数组
- (NSMutableArray *)arrayImageAnimationRightWithNum:(int)num
{
_arrayImageAnimation = [NSMutableArray arrayWithCapacity:0];
for (int i = 6; i > 0; i--)
{
NSString *str = [NSString stringWithFormat:@"animation_%d_%d",num,i];
UIImage *image = [UIImage imageNamed:str];
[_arrayImageAnimation addObject:image];
}
return _arrayImageAnimation;
}