NSURL+TransferFileFormat.m 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // NSURL+TransferFileFormat.m
  3. // VQU
  4. //
  5. // Created by CY on 2021/4/27.
  6. // Copyright © 2021 leo. All rights reserved.
  7. //
  8. #import "NSURL+TransferFileFormat.h"
  9. #import "lame.h"
  10. @implementation NSURL (TransferFileFormat)
  11. - (NSURL *)transformCAFToMP3{
  12. // 输入路径
  13. NSString *inPath = [self resourceSpecifier];
  14. // 输出路径
  15. NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
  16. NSString *outPath = [[NSURL URLWithString:[path stringByAppendingPathComponent:@"audioVerify.mp3"]] resourceSpecifier];
  17. @try {
  18. size_t read, write;
  19. FILE *pcm = fopen([inPath UTF8String], "rb"); //source 被转换的音频文件位置
  20. fseek(pcm, 4*1024, SEEK_CUR); //skip file header
  21. FILE *mp3 = fopen([outPath UTF8String], "wb"); //output 输出生成的Mp3文件位置
  22. const int PCM_SIZE = 8192;
  23. const int MP3_SIZE = 8192;
  24. short int pcm_buffer[PCM_SIZE*2];
  25. unsigned char mp3_buffer[MP3_SIZE];
  26. lame_t lame = lame_init();
  27. int rateKey = 44100;
  28. int numOfChannelsKey = 2;
  29. lame_set_in_samplerate(lame, rateKey);
  30. lame_set_VBR(lame, vbr_default);
  31. lame_set_num_channels(lame, numOfChannelsKey);//设置1为单通道,默认为2双通道
  32. lame_set_quality(lame, 0); /* 2=high 5 = medium 7=low 音质*/
  33. lame_init_params(lame);
  34. do {
  35. size_t size = (size_t)(2 * sizeof(short int));
  36. read = fread(pcm_buffer, size, PCM_SIZE, pcm);
  37. if (read == 0)
  38. write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
  39. else
  40. write = lame_encode_buffer_interleaved(lame, pcm_buffer, (int)read, mp3_buffer, MP3_SIZE);
  41. fwrite(mp3_buffer, write, 1, mp3);
  42. } while (read != 0);
  43. lame_close(lame);
  44. fclose(mp3);
  45. fclose(pcm);
  46. }
  47. @catch (NSException *exception) {
  48. NSLog(@"%@",[exception description]);
  49. }
  50. @finally {
  51. NSLog(@"MP3生成成功:");
  52. }
  53. return [NSURL fileURLWithPath:outPath];
  54. }
  55. @end