天天看點

IOS 通過lame架構 錄制 MP3 檔案

思路分享:

IOS無法直接錄制mp3檔案,先錄制蘋果支援的格式(caf、aac等),再借助第三方開源架構庫 lame 進行格式轉換。

具體實作

1、導入 lame 靜态庫;(https://download.csdn.net/download/kiusoft/10721707)

IOS 通過lame架構 錄制 MP3 檔案

2、引用頭檔案:

a、#import <AVFoundation/AVFoundation.h>

b、#import "lame.h";

3、核心轉換:

  1. // 轉換為 mp3 格式的重要代碼
  2. - (void)toMp3:(NSString *)fName
  3. {
  4.     NSString *recordFilePath = [recorderPath stringByAppendingPathComponent:fName];
  5.     NSArray *tempFilePathArray = [fName componentsSeparatedByString:@"."];
  6.     NSString *mp3FileName = [tempFilePathArray[0] stringByAppendingString:@".mp3"];
  7.     NSString *mp3FilePath = [mp3Path stringByAppendingPathComponent:mp3FileName];
  8.     // 開始轉換
  9.     int read, write;
  10.     // 轉換的源檔案位置
  11.     FILE *pcm = fopen([recordFilePath cStringUsingEncoding:1], "rb");
  12.     // 轉換後儲存的位置
  13.     FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");
  14.     const int PCM_SIZE = 8192;
  15.     const int MP3_SIZE = 8192;
  16.     short int pcm_buffer[PCM_SIZE*2];
  17.     unsigned char mp3_buffer[MP3_SIZE];
  18.     // 建立這個工具類
  19.     lame_t lame = lame_init();
  20.     lame_set_in_samplerate(lame, 44100);
  21.     lame_set_VBR(lame, vbr_default);
  22.     lame_init_params(lame);
  23.     //doWhile 循環
  24.     do {
  25.         read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
  26.         if (read == 0){
  27.             //這裡面的代碼會在最後調用 隻會調用一次
  28.             write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
  29.             //NSLog(@"read0%d",write);
  30.         }
  31.         else{
  32.             //這個 write 是寫入檔案的長度 在此區域内會一直調用此内中的代碼 一直再壓縮 mp3檔案的大小,直到不滿足條件才退出
  33.             write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
  34.             //寫入檔案  前面第一個參數是要寫入的塊 然後是寫入資料的長度 聲道 儲存位址
  35.             fwrite(mp3_buffer, write, 1, mp3);
  36.             //NSLog(@"read%d",write);
  37.         }
  38.     } while (read != 0);
  39.     lame_close(lame);
  40.     fclose(mp3);
  41.     fclose(pcm);
  42. }