录音1分钟:
caf格式用了2.6MB
mp3格式用了227KB
录音10分钟:
caf格式用了26.5MB
mp3格式用了2.3MB
1.导入lame
gitbub地址:
https://github.com/hedgehogIda/caf-mp3
2.声明头文件
#import "lame.h"
3.实现代码
我的博客中实现录音功能的这篇文章(https://www.jianshu.com/p/fea0cbe42cb2),里面有获取tmpUrl的代码
/**
caf转MP3
*/
- (void)conventToMp3 {
//tmpUrl是caf文件的路径,并转换成字符串
NSString *cafFilePath = [tmpUrl absoluteString];
//存储mp3文件的路径
NSString *mp3FilePath = [NSString stringWithFormat:@"%@.mp3",[NSString stringWithFormat:@"%@",[cafFilePath substringToIndex:cafFilePath.length - 4]]];
@try {
int read, write;
FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
fseek(pcm, 4*1024, SEEK_CUR); //skip file header
FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "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_in_samplerate(lame, 11025.0);
lame_set_VBR(lame, vbr_default);
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);
NSLog(@"转换成功");
}
@catch (NSException *exception) {
NSLog(@"%@",[exception description]);
}
@finally {
}
}