我正在尝试合并AVSSET阵列中的视频,但我只能获得第一个和最后一个视频。阵列之间的视频显示黑色区域。
检查我使用的代码。
func mergeVideoArray() {
let mixComposition = AVMutableComposition()
for videoAsset in videoURLArray {
let videoTrack =
mixComposition.addMutableTrack(withMediaType: AVMediaType.video,
preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do {
try videoTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration),
of: videoAsset.tracks(withMediaType: AVMediaType.video).first!,
at: totalTime)
videoSize = (videoTrack?.naturalSize)!
} catch let error as NSError {
print("error: \(error)")
}
let trackArray = videoAsset.tracks(withMediaType: .audio)
if trackArray.count > 0 {
let audioTrack =
mixComposition.addMutableTrack(withMediaType: AVMediaType.audio,
preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do {
try audioTrack?.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset.duration), of: videoAsset.tracks(withMediaType: AVMediaType.audio).first!, at: audioTime)
audioTime = audioTime + videoAsset.duration
}
catch {
}
}
totalTime = totalTime + videoAsset.duration
let videoInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack!)
if videoAsset != videoURLArray.last{
videoInstruction.setOpacity(0.0, at: videoAsset.duration)
}
layerInstructionsArray.append(videoInstruction)
}
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, totalTime)
mainInstruction.layerInstructions = layerInstructionsArray
let mainComposition = AVMutableVideoComposition()
mainComposition.instructions = [mainInstruction]
mainComposition.frameDuration = CMTimeMake(1, 30)
mainComposition.renderSize = CGSize(width: videoSize.width, height: videoSize.height)
let url = "merge_video".outputURL
let exporter = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
exporter!.outputURL = url
exporter!.outputFileType = AVFileType.mov
exporter!.shouldOptimizeForNetworkUse = false
exporter!.videoComposition = mainComposition
exporter!.exportAsynchronously {
let video = AVAsset(url: url)
let playerItem = AVPlayerItem(asset: video)
let player = AVPlayer(playerItem: playerItem)
self.playerViewController.player = player
self.present(self.playerViewController, animated: true) {
self.playerViewController.player!.play()
}
}
}
请帮助我解决此问题。提前谢谢。
笔记
我可以从阵列创建视频,但视频中仅显示第一个和最后一个索引值。对于其余值,仅显示空白屏幕。