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.     
  6.     NSArray *tempFilePathArray = [fName componentsSeparatedByString:@"."];
  7.     NSString *mp3FileName = [tempFilePathArray[0] stringByAppendingString:@".mp3"];
  8.     NSString *mp3FilePath = [mp3Path stringByAppendingPathComponent:mp3FileName];
  9.     
  10.     // 开始转换
  11.     int read, write;
  12.     
  13.     // 转换的源文件位置
  14.     FILE *pcm = fopen([recordFilePath cStringUsingEncoding:1], "rb");
  15.     // 转换后保存的位置
  16.     FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");
  17.     
  18.     const int PCM_SIZE = 8192;
  19.     const int MP3_SIZE = 8192;
  20.     short int pcm_buffer[PCM_SIZE*2];
  21.     unsigned char mp3_buffer[MP3_SIZE];
  22.     
  23.     // 创建这个工具类
  24.     lame_t lame = lame_init();
  25.     lame_set_in_samplerate(lame, 44100);
  26.     lame_set_VBR(lame, vbr_default);
  27.     lame_init_params(lame);
  28.     //doWhile 循环
  29.     do {
  30.         read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
  31.         if (read == 0){
  32.             //这里面的代码会在最后调用 只会调用一次
  33.             write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
  34.             //NSLog(@"read0%d",write);
  35.         }
  36.         else{
  37.             //这个 write 是写入文件的长度 在此区域内会一直调用此内中的代码 一直再压缩 mp3文件的大小,直到不满足条件才退出
  38.             write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
  39.             
  40.             //写入文件  前面第一个参数是要写入的块 然后是写入数据的长度 声道 保存地址
  41.             fwrite(mp3_buffer, write, 1, mp3);
  42.             //NSLog(@"read%d",write);
  43.         }
  44.     } while (read != 0);
  45.     
  46.     lame_close(lame);
  47.     
  48.     fclose(mp3);
  49.     fclose(pcm);
  50. }