1. 程式人生 > >swift 錄制多個音頻 並將音頻轉換為mp3 並合成多個mp3文件為一個文件

swift 錄制多個音頻 並將音頻轉換為mp3 並合成多個mp3文件為一個文件

art sta ttr 錄制 cti record buffer hub 上傳

我的需求是可以錄制多個文件,最後生成的文件格式為mp3形式,查了下各種資料,因為swift無法直接將音頻錄制為mp3格式,所以最後我采取的解決方案為先將每個單獨的文件轉為mp3,最後逐一合並形成一個mp3文件

首先第一步錄制 簡單說明下:

  參考: http://www.jianshu.com/p/09af208a5663(感謝) http://www.hangge.com/blog/cache/detail_772.html(感謝)

  1. 音頻配置,我嘗試了下盡可能多加各種配置最後有問題,測試成功的配置如下  

 recorderSeetingsDic: [String: Any] = [
        AVSampleRateKey: NSNumber(value: 16000),//采樣率
        AVFormatIDKey: NSNumber(value: kAudioFormatLinearPCM),//音頻格式
        AVNumberOfChannelsKey: NSNumber(value: 2),//通道數
        AVEncoderAudioQualityKey: NSNumber(value: AVAudioQuality.min.rawValue)//錄音質量
 ]

  2,錄制實現(部分代碼)

//音頻路徑
let audioPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first?.appending("/test.caf"))!

  

let session:AVAudioSession = AVAudioSession.sharedInstance()

try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)

try! session.setActive(true)

do {
                recorder = try AVAudioRecorder(url: URL(string: audioPath)!, settings: recorderSeetingsDic)
                
                //開啟儀表計數功能
                recorder!.isMeteringEnabled = true
                //準備錄音
                recorder!.prepareToRecord()

                recorder?.record()
            } catch let err {
                print("錄音失敗:\(err.localizedDescription)")
}

  第二步將錄制的多個caf格式音頻轉為一個mp3文件,(最初采用的方式是將多個.caf文件合成為m4a文件的 但是找不到m4a轉為mp3的解決方法,用lame也行不通,很郁悶)

  1.首先要編譯lame 這是將.caf轉為mp3第一步,有很多可以參考的方式

    我參考的編譯方式:http://blog.csdn.net/cating1314/article/details/46046497(感謝)

    我們需要編譯過後的libmp3lame.a與lame.h兩個文件,都在編譯過後的thin-lame與fat-lame文件中。根據自己的需求選取,我采用的是fat-lame中的兩個文件

    不想編譯的話可以采用我的,應該也不會有啥問題 https://pan.baidu.com/s/1dFepCIl 提取密碼:reck

  2轉換以及合成方法 (轉換與合成均采用OC寫的)

  參考: https://github.com/CharmingLee/RecordingDemo(感謝)

  定義了兩個文件convertMp3.h與convertMp3.m

  convertMp3.h文件

  

#import <UIKit/UIKit.h>

@interface convertMp3: NSObject

- (void) audioPCMtoMP3:(NSString *)audioFileSavePath mp3File:(NSString *)mp3FilePath mergeFile:(NSString *)mergeFilePath;

@end

  convertMp3.m文件

#import "convertMp3.h"
#import "lame.h"

#define KFILESIZE (1 * 1024 * 1024)

@interface convertMp3()

@end

@implementation convertMp3

- (void)audioPCMtoMP3 :(NSString *)audioFileSavePath mp3File:(NSString *)mp3FilePath mergeFile:(NSString *)mergeFilePath
{
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([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, 16000);
        lame_set_VBR(lame, vbr_off);
        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 {
        //從第二個文件才開始合並 第一個文件mergeFilePath與mp3FilePath相同 即第一個轉換後的文件地址就是最終合成的完整的mp3文件地址
        if([mergeFilePath isEqualToString:mp3FilePath] == NO) {
            [self pieceFileA:mergeFilePath withFileB:mp3FilePath];
        }
    }
    
}

- (BOOL)pieceFileA:(NSString *)filePathA withFileB:(NSString *)filePathB {
    //合成過後的文件路徑 之後不管多少文件 都是在這個filePathA文件之後繼續寫入的
    NSString *synthesisFilePath = filePathA;
    
    // 更新的方式讀取文件A
    NSFileHandle *handleA = [NSFileHandle fileHandleForUpdatingAtPath:synthesisFilePath];
    [handleA seekToEndOfFile];
    
    NSDictionary *fileBDic =
    [[NSFileManager defaultManager] attributesOfItemAtPath:filePathB
                                                     error:nil];
    long long fileSizeB = fileBDic.fileSize;
    
    // 大於xM分片拼接xM
    if (fileSizeB > KFILESIZE) {
        
        // 分片
        long long pieces = fileSizeB / KFILESIZE; // 整片
        long long let = fileSizeB % KFILESIZE;    // 剩余片
        
        long long sizes = pieces;
        // 有余數
        if (let > 0) {
            // 加多一片
            sizes += 1;
        }
        
        NSFileHandle *handleB = [NSFileHandle fileHandleForReadingAtPath:filePathB];
        for (int i = 0; i < sizes; i++) {
            
            [handleB seekToFileOffset:i * KFILESIZE];
            NSData *tmp = [handleB readDataOfLength:KFILESIZE];
            [handleA writeData:tmp];
        }
        
        [handleB synchronizeFile];
        
        // 大於xM分片讀xM(最後一片可能小於xM)
    } else {
        
        [handleA writeData:[NSData dataWithContentsOfFile:filePathB]];
    }
    
    [handleA synchronizeFile];
     NSLog(@"合並完成");
    // 將B文件刪除
    //    [[NSFileManager defaultManager] removeItemAtPath:filePathB error:nil];
    
    return YES;
}

@end

  在橋接文件中加入頭文件 #import "convertMp3.h"

  3.調用OC文件開始合並

 

//合並
    func transferAudio(num: Int) {
        
        let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! as NSURL
        let stringDate = BaseController().getCurrentTimeMillisecond()
        let mp3Path: URL = (documentDirectoryURL.appendingPathComponent(BaseController().randomMD5(str: stringDate) + ".mp3")! as URL as NSURL) as URL!
        
        if num == 0 {
            self.audioPath = mp3Path.path
        }
        
        convertMp3().audioPCMtoMP3(self.audioLocalUrls[num],mp3File: mp3Path.path,mergeFile: self.audioPath)
        
        if num == self.audioLocalUrls.count - 1{
            self.uploadAudio()//上傳
        }else{
            let order = num + 1
            transferAudio(num: order)
        }
    }

 調用transferAudio(num:0) 開始一個一個caf文件轉換合並 這樣流程走通了 錄制多個caf文件 逐個將其轉為mp3 在合並為一個完整mp3文件,剛接觸swift沒多長時間 東拼西湊實現的功能 如果有哪裏不對 希望及時告訴我 謝謝,希望對其它有次需求的人有個參考,畢竟折磨我很長時間

  

swift 錄制多個音頻 並將音頻轉換為mp3 並合成多個mp3文件為一個文件