設(shè)置audiorecorder參數(shù)問題這里就不多說了,網(wǎng)上有很多例子。我們要做的是把錄出來的比較大的pcm音頻文件實(shí)時(shí)壓縮轉(zhuǎn)碼成mp3文件,這樣在播放時(shí)能更加快速,并且與安卓、h5播放器也好做到統(tǒng)一。設(shè)置好audiorecorder,開始錄音,也就是record后,開一個(gè)線程,插入我們的轉(zhuǎn)碼代碼。
[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);//設(shè)置1為單通道,默認(rèn)為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;
}
//獲取轉(zhuǎn)化后的mp3地址
-(NSString*)getmp3SavePath1{
NSString*urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
urlStr=[urlStrstringByAppendingPathComponent:SPMP3RecordAudioFile];
returnurlStr;
}