iOS 使用lamemp3库将PCM录音数据压缩为MP3格式

根据pcm文件转MP3

  • (void)conventToMp3 {
    NSString *cafFilePath = [NSTemporaryDirectory() stringByAppendingString:@"VoiceInputFile"];
    self.mp3FilePath = [[NSUUID UUID] UUIDString];
    self.mp3FilePath = [self.mp3FilePath stringByAppendingString:@".mp3"];
    NSString *mp3FilePath = [[NSHomeDirectory() stringByAppendingFormat:@"/Documents/"] stringByAppendingPathComponent:self.mp3FilePath];

    @try {

      int read, write;
      
      FILE *pcm = fopen([cafFilePath cStringUsingEncoding:NSASCIIStringEncoding], "rb");
      FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:NSASCIIStringEncoding], "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, self.sampleRate);
      lame_set_VBR(lame, vbr_default);
      lame_init_params(lame);
      
      long curpos;
      BOOL isSkipPCMHeader = NO;
      
      do {
          
          curpos = ftell(pcm);
          
          long startPos = ftell(pcm);
          
          fseek(pcm, 0, SEEK_END);
          long endPos = ftell(pcm);
          
          long length = endPos - startPos;
          
          fseek(pcm, curpos, SEEK_SET);
          
          
          if (length > PCM_SIZE * 2 * sizeof(short int)) {
              
              if (!isSkipPCMHeader) {
                  //Uump audio file header, If you do not skip file header
                  //you will heard some noise at the beginning!!!
                  fseek(pcm, 4 * 1024, SEEK_SET);
                  isSkipPCMHeader = YES;
              }
              
              read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
              write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
              fwrite(mp3_buffer, write, 1, mp3);
          }
          
          else {
              
              [NSThread sleepForTimeInterval:0.05];
          }
          
      } while (!self.isStopRecorde);
      
      read = (int)fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
      write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
      lame_close(lame);
      fclose(mp3);
      fclose(pcm);
      
      self.isFinishConvert = YES;
    

    }
    @catch (NSException *exception) {

    }
    @finally {

    }
    }

参数设置
/** mp3压缩参数 /
_lame = lame_init();
/
* 单声道 /
lame_set_num_channels(_lame, 1);
/
* 16K采样率 决定 音质 清晰度 /
lame_set_in_samplerate(_lame, 16000);
lame_set_out_samplerate(_lame, 16000);
/
* 压缩的比特率为16K 决定mp3 文件大小 */
lame_set_brate(_lame, 16);
仔细阅读以下博客 你会有所收获

实时格式化pcm --> mp3

http://code4app.com/forum.php?mod=viewthread&tid=6211

http://www.cnblogs.com/ios8/p/IOS-PCM-MP3.html

边录边转详解

http://ikinglai.blog.51cto.com/6220785/1228309

你可能感兴趣的:(iOS 使用lamemp3库将PCM录音数据压缩为MP3格式)