思路分享:
IOS無法直接錄制mp3檔案,先錄制蘋果支援的格式(caf、aac等),再借助第三方開源架構庫 lame 進行格式轉換。
具體實作
1、導入 lame 靜态庫;(https://download.csdn.net/download/kiusoft/10721707)
2、引用頭檔案:
a、#import <AVFoundation/AVFoundation.h>
b、#import "lame.h";
3、核心轉換:
- // 轉換為 mp3 格式的重要代碼
- - (void)toMp3:(NSString *)fName
- {
- NSString *recordFilePath = [recorderPath stringByAppendingPathComponent:fName];
- NSArray *tempFilePathArray = [fName componentsSeparatedByString:@"."];
- NSString *mp3FileName = [tempFilePathArray[0] stringByAppendingString:@".mp3"];
- NSString *mp3FilePath = [mp3Path stringByAppendingPathComponent:mp3FileName];
- // 開始轉換
- int read, write;
- // 轉換的源檔案位置
- FILE *pcm = fopen([recordFilePath cStringUsingEncoding:1], "rb");
- // 轉換後儲存的位置
- FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");
- 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, 44100);
- lame_set_VBR(lame, vbr_default);
- lame_init_params(lame);
- //doWhile 循環
- do {
- read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
- if (read == 0){
- //這裡面的代碼會在最後調用 隻會調用一次
- write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
- //NSLog(@"read0%d",write);
- }
- else{
- //這個 write 是寫入檔案的長度 在此區域内會一直調用此内中的代碼 一直再壓縮 mp3檔案的大小,直到不滿足條件才退出
- write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
- //寫入檔案 前面第一個參數是要寫入的塊 然後是寫入資料的長度 聲道 儲存位址
- fwrite(mp3_buffer, write, 1, mp3);
- //NSLog(@"read%d",write);
- }
- } while (read != 0);
- lame_close(lame);
- fclose(mp3);
- fclose(pcm);
- }