123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- //
- // NSURL+TransferFileFormat.m
- // VQU
- //
- // Created by CY on 2021/4/27.
- // Copyright © 2021 leo. All rights reserved.
- //
- #import "NSURL+TransferFileFormat.h"
- #import "lame.h"
- @implementation NSURL (TransferFileFormat)
- - (NSURL *)transformCAFToMP3{
- // 输入路径
- NSString *inPath = [self resourceSpecifier];
-
- // 输出路径
- NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- NSString *outPath = [[NSURL URLWithString:[path stringByAppendingPathComponent:@"audioVerify.mp3"]] resourceSpecifier];
- @try {
- size_t read, write;
-
- FILE *pcm = fopen([inPath UTF8String], "rb"); //source 被转换的音频文件位置
- fseek(pcm, 4*1024, SEEK_CUR); //skip file header
- FILE *mp3 = fopen([outPath UTF8String], "wb"); //output 输出生成的Mp3文件位置
-
- 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();
- int rateKey = 44100;
- int numOfChannelsKey = 2;
- lame_set_in_samplerate(lame, rateKey);
- lame_set_VBR(lame, vbr_default);
- lame_set_num_channels(lame, numOfChannelsKey);//设置1为单通道,默认为2双通道
- lame_set_quality(lame, 0); /* 2=high 5 = medium 7=low 音质*/
- lame_init_params(lame);
-
- do {
- size_t size = (size_t)(2 * sizeof(short int));
- read = fread(pcm_buffer, size, PCM_SIZE, pcm);
- if (read == 0)
- write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
- else
- write = lame_encode_buffer_interleaved(lame, pcm_buffer, (int)read, mp3_buffer, MP3_SIZE);
-
- fwrite(mp3_buffer, write, 1, mp3);
-
- } while (read != 0);
-
- lame_close(lame);
- fclose(mp3);
- fclose(pcm);
- }
- @catch (NSException *exception) {
- NSLog(@"%@",[exception description]);
- }
- @finally {
- NSLog(@"MP3生成成功:");
- }
- return [NSURL fileURLWithPath:outPath];
- }
- @end
|