iOS录音转码(MP3)
由于采用手机端系统的录音功能,为了让iOS和Android的录音在其他平台上能够正常播放,这是就需要对录音的文件进行转码,一般转成MP3格式,这里转码用的三方库是lame
ios端对于录音转码的源码如下:
//音频转码
- (void)audio_mp3
{
NSString *cafFilePath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
cafFilePath = [cafFilePath stringByAppendingPathComponent:kRecordAudioFile];
NSString *mp3FilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];
mp3FilePath = [mp3FilePath stringByAppendingPathComponent:@"myRecord1.mp3"];
@try{
intread, write;
FILE*pcm =fopen([cafFilePath cStringUsingEncoding:NSASCIIStringEncoding],"rb");
fseek(pcm,4*1024,SEEK_CUR);
FILE*mp3 =fopen([mp3FilePath cStringUsingEncoding:NSASCIIStringEncoding],"wb");
const int PCM_SIZE =8192;
const int MP3_SIZE =8192;
short int pcm_buffer[PCM_SIZE *2];
unsigned char mp3_buffer[MP3_SIZE];
lame_t lame =lame_init();
lame_set_in_samplerate(lame, 11025.0);
lame_set_VBR(lame, vbr_default);
lame_init_params(lame);
do{
read = (int)fread(pcm_buffer, 2*sizeof(short int), 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(@"%@",[exception description]);
}
@finally{
NSLog(@"MP3生成成功: %@",mp3FilePath);
}
}
音频转码的代码就这些,希望能对大家有一点的帮助。