2016-12-07 29 views
0

我正在使用AVFoundation框架。我只是想添加三個視頻合併爲一個視頻,但問題是我無法添加三個視頻。我想知道我們可以使用AVMutableComposition添加多少視頻。是否允許添加2個以上的視頻。任何幫助?AVMutableComposition不允許添加4個視頻軌道

這裏是我的代碼

///////////////////////////////////////////// 
// 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") 
} 

回答

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秒鐘插入你的第三個視頻,這是已經有資產的軌道上的視頻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) 

作爲這種方法的獎勵,您實際上可以重寫您的代碼以使用循環和視頻資產陣列也使其更具可重用性。

+1

謝謝,很好的回答。但我以前解決過這個問題。這是我的錯誤。 – varinder