iOS 音频转码 使用lame转为MP3格式

由于AVAudioRecorder不能录制编码为MP3,所以就需要我们将录音后的音频文件格式进行转换(注意:AV Foundation和Core Audio提供对MP3数据解码的支持,但是不提供对其进行编码。所以我们要借助第三方库进行MP3编码)。如何转换?lame无疑是一个很好的选择,lame是一个开源音频压缩软件,目前是公认有损质量MP3中压缩效果最好的编码器。接下来直奔主题,介绍一下如何使用lame将音频转为MP3格式。

一、使用lame的准备工作

首先去官网下载lame库(下载地址),下载后需要将lame库进行编译(编译脚本下载地址)。编译步骤如下:
1、
在桌面上新建一个文件夹,然后将下载后的lame库文件解压命名为lame和编译脚本文件一同放到当前文件中,像这样:

iOS 音频转码 使用lame转为MP3格式_第1张图片
1370044-3a69132b1eaa6abd.png

2、
  打开终端,cd到lame-3.99.5目录中,运行脚本,开始编译。编译时间稍微有点长,编译成功后文件内容如下所示:

iOS 音频转码 使用lame转为MP3格式_第2张图片
aaa.png

新增加的这几个文件夹分别包含了不同的cpu架构,这里就不详细介绍。如果要支持所有的cpu架构(包括真机和模拟器),只需要将fat-lame文件中的内容拖到项目中即可(lame.h和libmp3lame.a)。至此,准备工作完毕。

二、lame的使用


//录音文件转码
- (void)audio_PCMtoMP3
{
    NSString *recorderSavePath = [self.savedRecordPath absoluteString];
    NSString *audioTemporarySavePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES) lastObject];
    NSString *mp3FileName = [self.savedRecordPath lastPathComponent];
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];
    NSString *mp3FilePath = [audioTemporarySavePath stringByAppendingPathComponent:mp3FileName];
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([recorderSavePath 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 = (int)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 {
        NSLog(@"MP3生成成功: %@",mp3FilePath);
        self.savedRecordPath = mp3FilePath.tzl_URL;
    }
    
}

你可能感兴趣的:(iOS 音频转码 使用lame转为MP3格式)