由于AVAudioRecorder不能錄制編碼為MP3,所以就需要我們將錄音后的音頻文件格式進行轉換(注意:AV Foundation和Core Audio提供對MP3數據解碼的支持,但是不提供對其進行編碼。所以我們要借助第三方庫進行MP3編碼)。如何轉換?lame無疑是一個很好的選擇,lame是一個開源音頻壓縮軟件,目前是公認有損質量MP3中壓縮效果最好的編碼器。接下來直奔主題,介紹一下如何使用lame將音頻轉為MP3格式。
一、使用lame的準備工作
首先去官網下載lame庫(下載地址),下載后需要將lame庫進行編譯(編譯腳本下載地址)。編譯步驟如下:
1、
在桌面上新建一個文件夾,然后將下載后的lame庫文件解壓命名為lame和編譯腳本文件一同放到當前文件中,像這樣:
1370044-3a69132b1eaa6abd.png
2、
打開終端,cd到lame-3.99.5目錄中,運行腳本,開始編譯。編譯時間稍微有點長,編譯成功后文件內容如下所示:
aaa.png
新增加的這幾個文件夾分別包含了不同的cpu架構,這里就不詳細介紹。如果要支持所有的cpu架構(包括真機和模擬器),只需要將fat-lame文件中的內容拖到項目中即可(lame.h和libmp3lame.a)。至此,準備工作完畢。
二、lame的使用
//錄音文件轉碼
- (void)audio_PCMtoMP3
{
NSString *recorderSavePath = [self.savedRecordPath absoluteString];
NSString *audioTemporarySavePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
NSString *mp3FileName = [self.savedRecordPath lastPathComponent];
mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
NSString *mp3FilePath = [audioTemporarySavePath stringByAppendingPathComponent:mp3FileName];
@try {
int read, write;
FILE *pcm = fopen([recorderSavePath 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 = (int)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(@"MP3生成成功: %@",mp3FilePath);
self.savedRecordPath = mp3FilePath.tzl_URL;
}
}