来源 :https://www.jianshu.com/p/06eaefee3314
/**
wav文件转mp3文件
@param wavPath wav文件路径(输入)
@param mp3Path mp3文件路径(输出)
*/
- (void)converWav:(NSString*)wavPathtoMp3:(NSString*)mp3PathsuccessBlock:(successBlock)block{
@try{
FILE *fwav = fopen([wavPath cStringUsingEncoding:NSASCIIStringEncoding], "rb");
fseek(fwav, 1024*4, SEEK_CUR); //跳过源文件的信息头,不然在开头会有爆破音
FILE *fmp3 = fopen([mp3Path cStringUsingEncoding:NSASCIIStringEncoding], "wb");
lame=lame_init();//初始化
lame_set_in_samplerate(lame, 44100.0); //设置wav的采样率
lame_set_num_channels(lame, 2); //声道,不设置默认为双声道
lame_init_params(lame);
constintPCM_SIZE =640*2;//双声道*2 单声道640即可
const int MP3_SIZE = 8800; //计算公式pcm_size * 1.25 + 7200
shortintpcm_buffer[PCM_SIZE];
unsignedcharmp3_buffer[MP3_SIZE];
intread, write;
do{
//将文件读进内存
read =fread(pcm_buffer,sizeof(shortint), PCM_SIZE, fwav);
if(read ==0) {
//当read为0,说明pcm文件已经全部读取完毕,调用lame_encode_flush即可。
write =lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
}else { //当read不为0,调用lame_encode_buffer_xxx进行转码
//双声道千万要使用lame_encode_buffer_interleaved这个函数
//32位、单声道需要调用其他函数,具体看代码后面的说明
write =lame_encode_buffer_interleaved(lame, pcm_buffer, read/2, mp3_buffer, MP3_SIZE);
}
//保存mp3文件
fwrite(mp3_buffer, write,1, fmp3);
}while(read !=0);
//记得各种关闭
lame_close(lame);
fclose(fmp3);
fclose(fwav);
}@catch(NSException *exception) {
NSLog(@"catch exception");
}@finally{
block();//成功转码后调用
}
}