實測音頻大小
錄音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.實現代碼
我的博客中實現錄音功能的這篇文章(http://www.lxweimin.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 {
}
}