ios 录音 音频转换

2017-02-08  本文已影响70人  每天刷两次牙

//语音文件

AVAudioRecorder*recorder;

NSTimer*timer;

NSString*urlPlay;

BOOLisPlay;

#pragma mark  ========= 语音文件 ==========

- (void)audio

{

AVAudioSession*a=[AVAudioSessionsharedInstance];

[asetCategory:AVAudioSessionCategoryPlayAndRecorderror:nil];

[asetActive:YESerror:nil];

//录音设置

NSMutableDictionary*recordSetting = [[NSMutableDictionaryalloc]init];

//录音格式 无法使用

[recordSetting setValue :[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];

//采样率

[recordSetting setValue :[NSNumbernumberWithFloat:44100]forKey:AVSampleRateKey];//44100.0

//通道数

[recordSetting setValue :[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];

//线性采样位数

[recordSetting setValue :[NSNumbernumberWithInt:16]forKey:AVLinearPCMBitDepthKey];

//音频质量,采样质量

[recordSettingsetValue:[NSNumbernumberWithInt:AVAudioQualityMin]forKey:AVEncoderAudioQualityKey];

NSString*strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];

urlPlay = [NSStringstringWithFormat:@"%@/lll.lpcm",strUrl];

NSError*error;

//初始化

recorder = [[AVAudioRecorderalloc]initWithURL:[NSURLURLWithString:urlPlay]settings:recordSettingerror:&error];

//开启音量检测

recorder.meteringEnabled=YES;

recorder.delegate=self;

}

//开始录音

- (IBAction)speak_touchDown:(id)sender {

if(isPlay==NO){

_speakBackView.frame=CGRectMake(ScreenWidth/2-75,ScreenHeight/2-130,150,150);

_speakBackView.backgroundColor=[UIColorcolorWithWhite:0.000alpha:0.6];

_speakBackView.layer.cornerRadius=10;

_speakBackView.clipsToBounds=YES;

[self.viewaddSubview:_speakBackView];

//创建录音文件,准备录音

if([recorderprepareToRecord]) {

//开始

[recorderrecord];

}

//设置定时检测

timer = [NSTimerscheduledTimerWithTimeInterval:0target:selfselector:@selector(detectionVoice)userInfo:nilrepeats:YES];

}

}

//拖动取消录音

- (IBAction)speak_drag:(id)sender {

if(isPlay==NO){

[_speakBackViewremoveFromSuperview];

//删除录制文件

[recorderdeleteRecording];

[recorderstop];

[timerinvalidate];

}

}

//录音完成

- (IBAction)speak_touchUpinset:(id)sender {

[timerinvalidate];

if(isPlay==NO) {

[_speakBackViewremoveFromSuperview];

doublecTime = recorder.currentTime;

if(cTime >1) {//如果录制时间<2 不发送

NSLog(@"发出去");

//显示录音时间

[_btn_speaksetTitle:[NSStringstringWithFormat:@"%.1lf\"播放",cTime]forState:UIControlStateNormal];

//录音时候的标志

UIImage*image=[UIImageimageNamed:@"speak_read"];

image=[imageimageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

[_btn_speaksetImage:imageforState:UIControlStateNormal];

_btn_cancelSpeak.hidden=NO;

isPlay=YES;

//新开线程进行解码

[NSThreaddetachNewThreadSelector:@selector(audio_PCMtoMP3)toTarget:selfwithObject:nil];

}else{

//删除记录的文件

[recorderdeleteRecording];

}

[recorderstop];

}

//点击时候播放与暂停

else{

if(self.avPlay.playing) {

[_btn_speaksetTitle:[NSStringstringWithFormat:@"%.1lf\"播放",_avPlay.duration]forState:UIControlStateNormal];

[self.avPlaystop];

return;

}

[_btn_speaksetTitle:@"暂停"forState:UIControlStateNormal];

AVAudioPlayer*player = [[AVAudioPlayeralloc]initWithContentsOfURL:[NSURLURLWithString:urlPlay]error:nil];

self.avPlay= player;

self.avPlay.delegate=self;

[self.avPlayprepareToPlay];

[self.avPlayplay];

NSLog(@"%f",_avPlay.duration);

}

}

//删除录音文件

- (IBAction)cancelSpeak:(id)sender {

[_avPlaystop];

_saveModel.speakUrl=nil;

[recorderdeleteRecording];

isPlay=NO;

_btn_cancelSpeak.hidden=YES;

[_btn_speaksetTitle:@"按住  说话"forState:UIControlStateNormal];

[_btn_speaksetImage:nilforState:UIControlStateNormal];

}

- (void)detectionVoice

{

[recorderupdateMeters];//刷新音量数据

//获取音量的平均值  [recorder averagePowerForChannel:0];

//音量的最大值  [recorder peakPowerForChannel:0];

doublelowPassResults = pow(10, (0.05* [recorderpeakPowerForChannel:0]));

NSLog(@"%lf",lowPassResults);

if(0

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_01"]];

}elseif(0.125

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_02"]];

}elseif(0.25

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_03"]];

}elseif(0.375

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_04"]];

}elseif(0.50

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_05"]];

}elseif(0.625

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_06"]];

}elseif(0.75

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_07"]];

}else{

[_speak_iamgeVsetImage:[UIImageimageNamed:@"record_animate_08"]];

}

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)playersuccessfully:(BOOL)flag{

[_btn_speaksetTitle:[NSStringstringWithFormat:@"%.1lf\"播放",_avPlay.duration]forState:UIControlStateNormal];

}

#pragma mark ===== 转换成MP3文件=====

- (void)audio_PCMtoMP3

{

NSString*strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];

//NSString *mp3FileName = [strUrl lastPathComponent];

//mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];

NSString*mp3FilePath = [strUrlstringByAppendingPathComponent:@"lll.mp3"];

@try{

intread, write;

FILEFILE*pcm = fopen([urlPlaycStringUsingEncoding:1],"rb");//source 被转换的音频文件位置

fseek(pcm,4*1024, SEEK_CUR);//skip file header

FILEFILE*mp3= fopen([mp3FilePathcStringUsingEncoding:1],"wb");//output 输出生成的Mp3文件位置

constintPCM_SIZE =8192;

constintMP3_SIZE =8192;

shortintpcm_buffer[PCM_SIZE*2];

unsignedcharmp3_buffer[MP3_SIZE];

lame_t lame = lame_init();

lame_set_in_samplerate(lame,44100);

lame_set_VBR(lame, vbr_default);

lame_init_params(lame);

do{

read = fread(pcm_buffer,2*sizeof(shortint), PCM_SIZE, pcm);

if(read ==0)

write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);

else

write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);

fwrite(mp3_buffer, write,1, mp3);

}while(read !=0);

lame_close(lame);

fclose(mp3);

fclose(pcm);

}

@catch(NSException*exception) {

NSLog(@"%@",[exceptiondescription]);

}

@finally{

strUrl = mp3FilePath;

_saveModel.speakUrl=[NSURLURLWithString:strUrl];

NSLog(@"MP3生成成功: %@",strUrl);

}

}

#pragma mark  ========= 上传 ==========

[self.httpMgrPOST:@"http://xuyingtest.sinaapp.com/uploadfile.php"parameters:nilconstructingBodyWithBlock:^void(id formData) {

[formDataappendPartWithFileURL:self.audioReorder.urlname:@"file"error:nil];

}success:^void(AFHTTPRequestOperation* operation,idresponseObject) {

NSDictionary*dict=[NSJSONSerializationJSONObjectWithData:responseObjectoptions:NSJSONReadingAllowFragmentserror:nil];

if(dict[@"error"]) {

NSLog(@" up success error :%@",dict[@"error"]);

}

else

{

NSLog(@"upload file ok!:%@",dict[@"success"]);

}

}failure:^void(AFHTTPRequestOperation* operation,NSError* error) {

NSLog(@"%@",error.localizedDescription);

}];

上一篇下一篇

猜你喜欢

热点阅读