swift 錄制多個(gè)音頻 并將音頻轉(zhuǎn)換為mp3 并合成多個(gè)mp3文件為一個(gè)文件

我的需求是可以錄制多個(gè)文件,最后生成的文件格式為mp3形式,查了下各種資料,因?yàn)閟wift無(wú)法直接將音頻錄制為mp3格式,所以最后我采取的解決方案為先將每個(gè)單獨(dú)的文件轉(zhuǎn)為mp3,最后逐一合并形成一個(gè)mp3文件

首先第一步錄制 簡(jiǎn)單說(shuō)明下:
參考: http://www.itdecent.cn/p/09af208a5663(感謝)
http://www.hangge.com/blog/cache/detail_772.html(感謝)
1. 音頻配置,我嘗試了下盡可能多加各種配置最后有問(wèn)題,測(cè)試成功的配置如下

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

2,錄制實(shí)現(xiàn)(部分代碼)

//音頻路徑
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)
                 
                //開啟儀表計(jì)數(shù)功能
                recorder!.isMeteringEnabled = true
                //準(zhǔn)備錄音
                recorder!.prepareToRecord()
 
                recorder?.record()
            } catch let err {
                print("錄音失敗:\(err.localizedDescription)")
}

第二步將錄制的多個(gè)caf格式音頻轉(zhuǎn)為一個(gè)mp3文件,(最初采用的方式是將多個(gè).caf文件合成為m4a文件的 但是找不到m4a轉(zhuǎn)為mp3的解決方法,用lame也行不通,很郁悶)
1.首先要編譯lame 這是將.caf轉(zhuǎn)為mp3第一步,有很多可以參考的方式
我參考的編譯方式:http://blog.csdn.net/cating1314/article/details/46046497(感謝)
我們需要編譯過(guò)后的libmp3lame.a與lame.h兩個(gè)文件,都在編譯過(guò)后的thin-lame與fat-lame文件中。根據(jù)自己的需求選取,我采用的是fat-lame中的兩個(gè)文件

不想編譯的話可以采用我的,應(yīng)該也不會(huì)有啥問(wèn)題 https://pan.baidu.com/s/1dFepCIl 提取密碼:reck

2轉(zhuǎn)換以及合成方法 (轉(zhuǎn)換與合成均采用OC寫的)
參考: https://github.com/CharmingLee/RecordingDemo(感謝)
定義了兩個(gè)文件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 被轉(zhuǎn)換的音頻文件位置
        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 {
        //從第二個(gè)文件才開始合并 第一個(gè)文件mergeFilePath與mp3FilePath相同 即第一個(gè)轉(zhuǎn)換后的文件地址就是最終合成的完整的mp3文件地址
        if([mergeFilePath isEqualToString:mp3FilePath] == NO) {
            [self pieceFileA:mergeFilePath withFileB:mp3FilePath];
        }
    }
     
}
 
- (BOOL)pieceFileA:(NSString *)filePathA withFileB:(NSString *)filePathB {
    //合成過(guò)后的文件路徑 之后不管多少文件 都是在這個(gè)filePathA文件之后繼續(xù)寫入的
    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;
        // 有余數(shù)
        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.調(diào)用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)
        }
    }

調(diào)用transferAudio(num:0) 開始一個(gè)一個(gè)caf文件轉(zhuǎn)換合并 這樣流程走通了 錄制多個(gè)caf文件 逐個(gè)將其轉(zhuǎn)為mp3 在合并為一個(gè)完整mp3文件,剛接觸swift沒(méi)多長(zhǎng)時(shí)間 東拼西湊實(shí)現(xiàn)的功能 如果有哪里不對(duì) 希望及時(shí)告訴我 謝謝,希望對(duì)其它有次需求的人有個(gè)參考,畢竟折磨我很長(zhǎng)時(shí)間

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容