设置audiorecorder参数问题这里就不多说了,网上有很多例子。我们要做的是把录出来的比较大的pcm音频文件实时压缩转码成mp3文件,这样在播放时能更加快速,并且与安卓、h5播放器也好做到统一。设置好audiorecorder,开始录音,也就是record后,开一个线程,插入我们的转码代码。
[self.audioRecorderrecord]
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[selfconventToMp3];
});
- (void)conventToMp3 {
NSString*cafFilePath = [selfgetSavePath1];
NSString*mp3FilePath = [selfgetmp3SavePath1];
@try{
intread, write;
FILE*pcm =fopen([cafFilePathcStringUsingEncoding:NSASCIIStringEncoding],"rb");
FILE*mp3 =fopen([mp3FilePathcStringUsingEncoding:NSASCIIStringEncoding],"wb");
constintPCM_SIZE = 8192;
constintMP3_SIZE = 8192;
shortintpcm_buffer[PCM_SIZE * 2];
unsignedcharmp3_buffer[MP3_SIZE];
lame_tlame =lame_init();
lame_set_num_channels(lame,1);//设置1为单通道,默认为2双通道
lame_set_in_samplerate(lame, 44100.0);//11025.0
//lame_set_VBR(lame, vbr_default);
lame_set_brate(lame,32);
lame_set_mode(lame,3);
lame_set_quality(lame,2);
lame_init_params(lame);
longcurpos;
BOOLisSkipPCMHeader =NO;
do{
curpos =ftell(pcm);
longstartPos =ftell(pcm);
fseek(pcm, 0,SEEK_END);
longendPos =ftell(pcm);
longlength = endPos - startPos;
fseek(pcm, curpos,SEEK_SET);
if(length > PCM_SIZE * 2 *sizeof(shortint)) {
if(!isSkipPCMHeader) {
//Uump audio file header, If you do not skip file header
//you will heard some noise at the beginning!!!
fseek(pcm, 4 * 1024,SEEK_SET);
isSkipPCMHeader =YES;
}
read = (int)fread(pcm_buffer, 2 *sizeof(shortint), PCM_SIZE, pcm);
write =lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
fwrite(mp3_buffer, write, 1, mp3);
}
else{
[NSThreadsleepForTimeInterval:0.05];
}
}while(!self.isStopRecorde);
read = (int)fread(pcm_buffer, 2 *sizeof(shortint), PCM_SIZE, pcm);
write =lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
lame_close(lame);
fclose(mp3);
fclose(pcm);
//self.isFinishConvert = YES;
}
@catch(NSException *exception) {
//DWDLog(@"%@", [exception description]);
}
@finally{
//DWDLog(@"convert mp3 finish!!!");
}
}
//获取pcm地址
-(NSString*)getSavePath1{
NSString*urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
urlStr=[urlStrstringByAppendingPathComponent:SPRecordAudioFile];
returnurlStr;
}
//获取转化后的mp3地址
-(NSString*)getmp3SavePath1{
NSString*urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
urlStr=[urlStrstringByAppendingPathComponent:SPMP3RecordAudioFile];
returnurlStr;
}