需求
項目里有錄音機(jī)相關(guān)的代碼粒没,最近產(chǎn)品發(fā)現(xiàn)我們的錄音文件生成默認(rèn)是wav格式的揩抡,想加一個wav轉(zhuǎn)mp3的功能曲管,百度了一下扣猫,可以用lame的第三方框架實現(xiàn)。
一開始選擇的pod導(dǎo)入lame庫翘地,后來發(fā)現(xiàn)不支持pod庫不支持armv7架構(gòu)申尤,那么只能自己編譯,編譯過程在iOS 編譯 lame 庫衙耕,步驟及遇到的問題 總結(jié)講的很詳細(xì)昧穿,多謝前輩大神總結(jié)分享,這里不在贅述橙喘。編譯之后會有幾個架構(gòu)分著的.a文件和.h文件时鸵,也有綜合起來的.a文件和.h文件,看自己的需要放到工程里即可厅瞎。
lame編譯之后的文件
使用
把libmp3lame.a文件和lame.h放到工程里
#import <lame/lame.h> //把lame庫導(dǎo)入到文件內(nèi)
- (BOOL) convertMp3from:(NSString *)wavpath topath:(NSString *)mp3path
{
NSString *filePath =wavpath ; //wav格式的文件路徑
NSString *mp3FilePath = mp3path; // 生成mp3的路徑
BOOL isSuccess = NO;
if (filePath == nil || mp3FilePath == nil){
return isSuccess;
}
NSFileManager* fileManager=[NSFileManager defaultManager];
if([fileManager removeItemAtPath:mp3path error:nil])
{
NSLog(@"刪除");
}
@try {
int read, write;
FILE *pcm = fopen([filePath cStringUsingEncoding:1], "rb"); //source 被轉(zhuǎn)換的音頻文件位置
if (pcm) {
fseek(pcm, 4*1024, SEEK_CUR);
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, 16000.0);
lame_set_num_channels(lame, 1);//通道 默認(rèn)是2
lame_set_quality(lame, 1);//質(zhì)量
lame_set_VBR(lame, vbr_default);
lame_set_brate(lame, 16);
lame_set_mode(lame, 3);
lame_init_params(lame);
// lame_set_VBR_mean_bitrate_kbps(lame, 256);
do {
read = (int)fread(pcm_buffer, sizeof(short int), PCM_SIZE, pcm);
if (read == 0)
write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
else {
write = lame_encode_buffer(lame, pcm_buffer, NULL, read, mp3_buffer, MP3_SIZE);//聲道=1饰潜,這里和上邊 lame_set_num_channels(lame, 1)對應(yīng),如果是雙聲道和簸,用下邊注掉的那行代碼
// write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE); 聲道=2
}
fwrite(mp3_buffer, write, 1, mp3);
} while (read != 0);
lame_close(lame);
fclose(mp3);
fclose(pcm);
isSuccess = YES;
}
//skip file header
}
@catch (NSException *exception) {
NSLog(@"error");
}
@finally {
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
return isSuccess;
}
}
需要一定注意的事彭雾,音頻的聲道,lame_set_num_channels(lame, 1)
要與下邊的write = lame_encode_buffer...
相對應(yīng)锁保。