iOS wav/caf转MP3


// ps:需要添加libmp3lame.a静态库,引入lame.h,真机需关闭bitcode,百度文件地址: http://pan.baidu.com/s/1mhHrqeG 密码: bz8a

 

- (void)audio_PCMtoMP3

{

    

    // self.audioFileSavePath

//    NSString *mp3FileName = [_recordUrl lastPathComponent];

//    NSLog(@"%@",[_recordUrl lastPathComponent]);

//    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];

    NSString *mp3FilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.mp3"];

    //   _recordUrl = [NSTemporaryDirectory() stringByAppendingString:@"record.caf"];  _recordUrl是音频存储路径

    @try {

        int read, write;

        

        FILE *pcm = fopen([_recordUrl cStringUsingEncoding:1], "rb");  //source 被转换的音频文件位置

        fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header

        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "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();

        lame_set_in_samplerate(lame, 11025.0);

        lame_set_VBR(lame, vbr_default);

        lame_init_params(lame);

        

        do {

            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);

            if (read == 0)

                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);

            else

                write = lame_encode_buffer_interleaved(lame, pcm_buffer, 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 {

        _recordUrl = mp3FilePath;

        NSLog(@"MP3生成成功: %@",_recordUrl);

        self.voiceData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:_recordUrl]];

        [[NSFileManager defaultManager] removeItemAtURL:[NSURL fileURLWithPath:_recordUrl] error:nil]; // 生成文件移除原文件

    }

}

 

随笔随记,以免忘记


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM