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