I\'m trying to merge two videos I get after recording using the camera as a UIImagePickerController. I\'ve succeeded with combining the videos into one but I have some problems
You have two layers. You need to apply the rotation instruction to both layers in the composition. What you are doing here is applying the rotation instruction to only one of them. Get a reference to both elements in the video composition and apply separate instructions to the two layers.
Try using trackVideo
in the initializer for your layer Instruction so it will use the AVMutableCompositionTrack
's trackID
rather than the source asset's trackID
Update:
You only need one AVMutableVideoCompositionLayerInstruction
, so declare it before the loop with the AVMutableCompositionTrack
as the parameter. Then on each iteration of the loop, set the necessary properties of the layer instruction (transform, crop rect) for the current video asset you're working with. You're controlling how the video content in the composition track should be displayed at each insert time.
At the end, place the single layerInstruction in the instructions array, and use that in the video composition.
var layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: trackVideo)
for i in 0...(videos.count-1){
//...your other code here
layerInstruction.setTransform(assetTrack.preferredTransform, atTime: insertTime)
layerInstruction.setCropRectangle(CGRectMake(0, 0, 300, 300), atTime: insertTime)
}
var instruction = AVMutableVideoCompositionInstruction();
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, insertTime);
instruction.layerInstructions = NSArray(object: layerInstruction);
var mainCompositionInst = AVMutableVideoComposition()
mainCompositionInst.instructions = NSArray(object: instruction)
You can just use this simple code,It works for me:
var assetVideoTrack = (sourceAsset.tracksWithMediaType(AVMediaTypeVideo)).last as! AVAssetTrack
var compositionVideoTrack = (composition.tracksWithMediaType(AVMediaTypeVideo)).last as! AVMutableCompositionTrack
if (assetVideoTrack.playable && compositionVideoTrack.playable) {
compositionVideoTrack.preferredTransform = assetVideoTrack.preferredTransform
}