工作中或許會遇到這樣的需求:將兩段不同的音頻合成一個音頻(暫且稱之為音頻拼接)。實現起來相對簡單,在介紹如何拼接之前,先了解 AVFoundation 下的幾個基本知識點。
AVAsset:正如官網文檔所述——「AVAsset 是一個抽象類,用來代表定時的視聽媒體,如視頻與聲音。每個 asset 包含一組 track,意圖一起呈現或處理,且媒體類型一致,包括但不限於音頻、視頻、文本、隱藏式字幕與字幕」。大致就是說 AVAsset 是 AVFoundation 中的抽象類,用來代表多媒體資源,如音頻、視頻等。
AVURLAsset:AVAsset 的子類,是一個具體類,用 URL 進行初始化。
AVMutableComposition:結合媒體資料,可視為 track(音頻軌道)的集合,用來合成音視頻。
AVMutableCompositionTrack:表示一個 track,包含媒體類型、音軌標識符等資訊,可插入、刪除、縮放 track 片段。
AVAssetTrack:表示素材軌道。
AVAssetExportSession:用來對一個 AVAsset 源物件進行轉碼,並導出為事先設定好的格式。
介紹完基本知識,接下來說明如何實現音頻拼接。
1、首先,取得本地的兩個音頻素材(一首五環之歌和 iPhone 的預設通知提示音):
NSString *auidoPath1 = [[NSBundle mainBundle] pathForResource:@"三全音" ofType:@"mp3"];
NSString *audioPath2 = [[NSBundle mainBundle] pathForResource:@"五環之歌" ofType:@"mp3"];
AVURLAsset *audioAsset1 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:auidoPath1]];
AVURLAsset *audioAsset2 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:audioPath2]];2、接下來建立兩個音頻軌道,並取得工程中兩個音頻素材的軌道:
AVMutableComposition *composition = [AVMutableComposition composition];
// 音頻軌道
AVMutableCompositionTrack *audioTrack1 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
AVMutableCompositionTrack *audioTrack2 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
// 音頻素材軌道
AVAssetTrack *audioAssetTrack1 = [[audioAsset1 tracksWithMediaType:AVMediaTypeAudio] firstObject];
AVAssetTrack *audioAssetTrack2 = [[audioAsset2 tracksWithMediaType:AVMediaTypeAudio] firstObject];3、將兩段音頻插入音軌檔案進行合併:
// 音頻合併 - 插入音軌檔案
[audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration) ofTrack:audioAssetTrack1 atTime:kCMTimeZero error:nil];
[audioTrack2 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset2.duration) ofTrack:audioAssetTrack2 atTime:kCMTimeZero error:nil];4、最後用 AVAssetExportSession 導出合併後的音頻檔案:
// 合併後的檔案導出 - 音頻檔案目前只找到合成 m4a 類型的
AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
NSString *outPutFilePath = [[self.filePath stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"xindong.m4a"];
session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
session.outputFileType = AVFileTypeAppleM4A;
[session exportAsynchronouslyWithCompletionHandler:^{
NSLog(@"合併完成----%@", outPutFilePath);
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:outPutFilePath] error:nil];
[_player play];
}];對於音頻檔案的合成導出類型,目前只找到支援 .m4a 格式的(不確定是否支援其他類型)。導出檔案所支援的類型可透過 [session supportedFileTypes] 查看。
文章轉自 心董兒的簡書