AVMutableComposition不允许添加4个视频轨道

时间:2016-12-07 06:44:57

标签: ios swift avfoundation

我正在使用AVFoundation框架。我只想添加三个视频合并为一个视频,但问题是我无法添加三个视频。我想知道我们可以使用AVMutableComposition添加多少视频。是否允许添加2个以上的视频。有什么帮助吗?

这是我的代码

/////////////////////////////////////////////
// Add video tracks 1 to mutable compositon//
/////////////////////////////////////////////
let firstTrack = compostion.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do{
    try firstTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset1.duration),
            ofTrack: videoAsset1.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: kCMTimeZero)
}
catch{
    print("failed to add first track")
}
print("Time to add 1 track\(CMTimeGetSeconds(videoAsset1.duration))")

/////////////////////////////////////////////
// Add video tracks 2 to mutable compositon//
/////////////////////////////////////////////
let secondTrack = compostion.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do{
    try secondTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset2.duration),
            ofTrack: videoAsset2.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: videoAsset1.duration)
}
catch{
    print("failed to add second track")
}
print("Time to add second track\(CMTimeGetSeconds(videoAsset2.duration))")
/////////////////////////////////////////////
// Add video tracks 3 to mutable compositon//
/////////////////////////////////////////////
let thirdTrack = compostion.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do{
    try thirdTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset3.duration), ofTrack: videoAsset3.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: videoAsset2.duration)
}
catch{
    print("failed to add third track")
}

1 个答案:

答案 0 :(得分:0)

/////////////////////////////////////////////
// Add video tracks 3 to mutable compositon//
/////////////////////////////////////////////
let thirdTrack = compostion.addMutableTrackWithMediaType(AVMediaTypeVideo, preferredTrackID: Int32(kCMPersistentTrackID_Invalid))
do{
    try thirdTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset3.duration), ofTrack: videoAsset3.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: videoAsset2.duration)
}
catch{
    print("failed to add third track")
}

您正尝试在atTime上添加第三个视频:videoAsset2.duration,此时可能已有视频。

假设视频1为10秒,视频2为5秒。你真的试图在5秒内插入你的第3个视频,这是已经有资产的轨道上视频1的一半。

幸运的是,这很容易解决。

就个人而言,我保持这样的插入时间:

var insertionTime : CMTime = kCMTimeZero

然后,每次成功添加视频时,都可以增加insertionTime

insertionTime = CMTimeAdd(insertionTime, VideoAsset1.duration)

从那里开始,只需使用

try thirdTrack.insertTimeRange(CMTimeRangeMake(kCMTimeZero, videoAsset3.duration), ofTrack: videoAsset3.tracksWithMediaType(AVMediaTypeVideo)[0], atTime: insertionTime)

作为这种方法的奖励,您实际上可以重写代码以使用循环和视频资产数组,这使得它更具可重用性。