mp3格式的音频是现在最流行的格式了,而caf是苹果自带录音器所录的格式,在与android端、web端交流的话非常不便,所以,把caf格式的音频转换成mp3皆大欢喜
现在最主流的就是用lame框架来实现了
不过lame只支持32位的,这对64位的很坑
不过我们可以下载lame的源码然后自己转成64位的就可以用了
导出lame静态库具体操作步骤参考:http://www.jianshu.com/p/24e262abdb54
已导出成功的lame静态库下载地址:链接: https://pan.baidu.com/s/1pLHpBmj 密码: kfq9
lame库导入工程后 拷贝如下转码方法调用即可
特别注意:在录制caf文件时,需要使用双通道,否则在转换为MP3格式时,声音不对
#import "lame.h"
{
NSString *cafpath;
}
/**
caf转MP3
*/
- (void)audio_PCMtoMP3 {
// 已录制caf格式语音的本地存放路径
cafpath = [[LGSoundRecorder shareInstance] soundFilePath];
// 定义转码后mp3格式语音存放的路径
_mp3FilePath = [self recordPath];
// 拼接mp3语音文件名
_mp3FilePath=[_mp3FilePath stringByAppendingString:@"/MyAudioMemoMP3.mp3"];
@try {
int read, write;
FILE *pcm = fopen([cafpath cStringUsingEncoding:4], "rb"); //source 被转换的音频文件位置
if(pcm == NULL)
{
NSLog(@"file not found");
return;
}
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([_mp3FilePath cStringUsingEncoding:4], "wb"); //output 输出生成的Mp3文件位置
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_num_channels(lame,2);//设置1为单通道,默认为2双通道
lame_set_in_samplerate(lame, 8000.0);//11025.0
//lame_set_VBR(lame, vbr_default);
lame_set_brate(lame,8);
lame_set_mode(lame,3);
lame_set_quality(lame,2); /* 2=high 5 = medium 7=low 音质*/
lame_init_params(lame);
do {
read = 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(@"执行完成");
}
}