在組合媒體的過程當中,須要用到 AVComposition 類,其中對於音頻軌道能夠使用與視頻軌道同樣的不重疊組合方式,同時音頻軌道也能夠重疊在一個時間段內,實現一種混音的效果,同時還能夠設置不一樣軌道的音量變化。數組
組合媒體時,分別生成了組合視頻和音頻的 AVMutableCompositionTrack 類,實現混音效果只須要在插入音頻軌道時將時間軸直接覆蓋便可。bash
AVMutableCompositionTrack *audioCompositionTrack = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *audioTracck = [[targetAsset tracksWithMediaType:AVMediaTypeAudio] firstObject];
[audioCompositionTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, targetAsset.duration) ofTrack:audioTracck atTime:kCMTimeZero error:nil];
複製代碼
這樣生成的 AVMutableComposition 的多個音頻軌道會同時發聲。app
要調節某個音頻軌道的音量,須要用到 AVMutableAudioMix 類,這個類接受 AVMutableAudioMixInputParameters 對象做爲參數,AVMutableAudioMixInputParameters 則提供了兩種方法來設置音量,對於具體音量的變化範圍定義爲 0.0 到 1.0 之間。ui
其具體使用以下spa
NSArray<AVAssetTrack *> *audioAssetTracks = [[composition copy] tracksWithMediaType:AVMediaTypeAudio]; // 獲取音軌組合
AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
NSMutableArray<AVMutableAudioMixInputParameters *> *params = [NSMutableArray array];
__block CMTime cursor = kCMTimeZero;
[audioAssetTracks enumerateObjectsUsingBlock:^(AVAssetTrack * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { // 遍歷音軌
AVMutableAudioMixInputParameters *parameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:obj]; // 生成某一音軌的 AVMutableAudioMixInputParameters 對象
[parameters setVolumeRampFromStartVolume:begin toEndVolume:end timeRange:CMTimeRangeMake(cursor, obj.timeRange.duration)]; // 設置音量
begin = begin + end;
end = begin - end;
begin = begin - end;
cursor = CMTimeAdd(cursor, obj.timeRange.duration);
[params addObject:parameters]; // 加入到參數組合中
}];
audioMix.inputParameters = params;// 設置 audioMix 的參數組合
複製代碼
獲得 audioMix 後,能夠將其賦值給 AVPlayerItem 用於播放,也能夠賦值給 AVAssetExportSession 用於導出完整的媒體資源,還能夠賦值給 AVAssetReaderAudioMixOutput。code
要注意的是,對於同一音軌,設置音頻軌道的時間區間不能出現重疊,不然會拋出運行時異常視頻
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'The timeRange of a volume ramp must not overlap the timeRange of an existing volume ramp.'
複製代碼