SJVoiceTransform.m 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //
  2. // SJVoiceTransform.m
  3. // AudioDemo
  4. //
  5. // Created by 张赛赛 on 15/8/24.
  6. // Copyright (c) 2015年 张赛赛. All rights reserved.
  7. //
  8. #import "SJVoiceTransform.h"
  9. #import "lame.h"
  10. @interface SJVoiceTransform()
  11. //@property (strong , nonatomic)NSString * path;//存放音频沙河路径
  12. @end
  13. @implementation SJVoiceTransform
  14. +(NSString *)stransformToMp3ByUrlWithUrl:(NSString *)docPath
  15. {
  16. NSString *pathUrl = [NSString stringWithFormat:@"%@",docPath];//存储录音pcm格式音频地址
  17. NSString * mp3Url = pathUrl;
  18. NSString *mp3FilePath = [docPath stringByAppendingString:@".mp3"];//存放Mp3地址
  19. if (!mp3Url || !mp3FilePath) {
  20. return 0;
  21. }
  22. @try {
  23. int read, write;
  24. FILE *pcm = fopen([mp3Url cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
  25. //音频不能为空
  26. if (!pcm) {
  27. return nil;
  28. }
  29. fseek(pcm, 4*1024, SEEK_CUR); //skip file header
  30. FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
  31. const int PCM_SIZE = 8192;
  32. const int MP3_SIZE = 8192;
  33. short int pcm_buffer[PCM_SIZE*2];
  34. unsigned char mp3_buffer[MP3_SIZE];
  35. lame_t lame = lame_init();
  36. lame_set_num_channels(lame,1);
  37. lame_set_in_samplerate(lame, 8000.0); //11025.0
  38. //lame_set_VBR(lame, vbr_default);
  39. lame_set_brate(lame, 8);
  40. lame_set_mode(lame, 3);
  41. lame_set_quality(lame, 2);//
  42. lame_init_params(lame);
  43. do {
  44. read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
  45. if (read == 0)
  46. write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
  47. else
  48. write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
  49. fwrite(mp3_buffer, write, 1, mp3);
  50. } while (read != 0);
  51. lame_close(lame);
  52. fclose(mp3);
  53. fclose(pcm);
  54. }
  55. @catch (NSException *exception) {
  56. NSLog(@"%@",[exception description]);
  57. }
  58. @finally {
  59. NSLog(@"MP3生成成功: %@",mp3FilePath);
  60. }
  61. return mp3FilePath;
  62. }
  63. @end