ConvertMp3.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. //
  2. // ConvertMp3.m
  3. // SwiftRecorder
  4. //
  5. // Created by iOS on 2018/9/25.
  6. // Copyright © 2018 AidaHe. All rights reserved.
  7. //
  8. #import "ConvertMp3.h"
  9. #import "lame.h"
  10. #define KFILESIZE (1 * 1024 * 1024)
  11. @implementation ConvertMp3
  12. - (void) audioPCMtoMP3:(NSString *)audioFileSavePath mp3File:(NSString *)mp3FilePath{
  13. NSLog(@"转码开始---");
  14. CFAbsoluteTime startTime =CFAbsoluteTimeGetCurrent();
  15. @try {
  16. int read, write;
  17. FILE *pcm = fopen([audioFileSavePath cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
  18. fseek(pcm, 4*1024, SEEK_CUR); //skip file header
  19. FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
  20. const int PCM_SIZE = 8192;
  21. const int MP3_SIZE = 8192;
  22. short int pcm_buffer[PCM_SIZE*2];
  23. unsigned char mp3_buffer[MP3_SIZE];
  24. lame_t lame = lame_init();
  25. //设置声道1单声道,2双声道
  26. lame_set_num_channels(lame,1);
  27. lame_set_in_samplerate(lame, 8000.0);
  28. lame_set_VBR(lame, vbr_off);
  29. lame_init_params(lame);
  30. do {
  31. read = (int)fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
  32. if (read == 0)
  33. write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
  34. else
  35. write = lame_encode_buffer_interleaved(lame,pcm_buffer, read, mp3_buffer, MP3_SIZE);
  36. fwrite(mp3_buffer, write, 1, mp3);
  37. } while (read != 0);
  38. lame_close(lame);
  39. fclose(mp3);
  40. fclose(pcm);
  41. }
  42. @catch (NSException *exception) {
  43. NSLog(@"%@",[exception description]);
  44. }
  45. NSLog(@"转码结束----");
  46. CFAbsoluteTime linkTime = (CFAbsoluteTimeGetCurrent() - startTime);
  47. NSLog(@"Linked in %f ms", linkTime *1000.0);
  48. }
  49. @end