iOS 通過(lame)將錄製音頻轉換成Mp3

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。如需轉載請標註! https://blog.csdn.net/qq_34347441/article/details/53518798

爲了iPhone 與 Android 實現音頻互通. Mp3格式的音頻文件再好不過了.這裏主要用到lame(Mp3音頻編碼器).   

首先使用 AVAudioRecorder 進行音頻錄製之前,進行如下參數設置:(一定要設置成pcm線性編碼格式)

// 定義音頻的編碼參數, 決定錄製音頻文件的格式, 音質, 容量大小等, 建議採用AAC的編碼方式
    let recordSettings = [AVSampleRateKey: NSNumber(value: Float(44100.0)), // 聲音採樣率
                          AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM), // 編碼格式
                          AVNumberOfChannelsKey: NSNumber(value: 2), //採集音軌
                          AVEncoderAudioQualityKey: NSNumber(value: Int32(AVAudioQuality.medium.rawValue)), // 音頻質量
                          AVLinearPCMBitDepthKey: NSNumber(value: 16),
                          AVLinearPCMIsFloatKey: NSNumber(value: false),
                          AVLinearPCMIsBigEndianKey: NSNumber(value: false)]


lame 靜態庫主要有兩個核心文件:


1:lame庫加入工程中


2:核心轉換代碼(這裏的代碼直接引用oc的)(該處直接引用大神代碼)

- (void)audio_PCMtoMP3  
{  
    NSString *mp3FileName = [self.audioFileSavePath lastPathComponent];  
    mp3FileName = [mp3FileName stringByAppendingString:@".mp3"];  
    NSString *mp3FilePath = [self.audioTemporarySavePath stringByAppendingPathComponent:mp3FileName];  
      
    @try {  
        int read, write;  
          
        FILE *pcm = fopen([self.audioFileSavePath 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 {  
        self.audioFileSavePath = mp3FilePath;  
        NSLog(@"MP3生成成功: %@",self.audioFileSavePath);  
    }  
} 

lame靜態庫(支持64架構) https://pan.baidu.com/s/1dFHtTk9 提取碼: smiw

demo地址:https://github.com/songhaisheng/SGRecorder

簡書博客地址

https://www.jianshu.com/u/3c7c13f3dc6b

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章