gpt4 book ai didi

iphone - 在 Swift 中合并视频数组

转载 作者:行者123 更新时间:2023-11-28 06:02:11 25 4
gpt4 key购买 nike

我正在尝试合并来自 avssets 数组的视频,但我只能获得第一个和最后一个视频。阵列之间的视频显示黑色区域。检查我正在使用的代码。

    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()
}
}
}

请帮我解决这个问题。提前致谢。

注意 我可以从数组创建视频,但视频中只显示第一个和最后一个索引值。对于其余值,仅显示空白屏幕。

最佳答案

我刚刚解决了我的问题,只需要更新代码中的一行。请查看代码。

    if videoAsset != videoURLArray.last{
videoInstruction.setOpacity(0.0, at: totalTime)
}

注意:数组的每个值只需要改变下一个视频的at位置即可。

关于iphone - 在 Swift 中合并视频数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49297539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com