I'm trying to add text over a video but no matter what I do I get invalid composition error (-11841). I have followed tutorials, read through threads and nothing stands out as being wrong. I am combining 3 videos, and an audio track and that works great. I'm trying to add the text for the duration of the first video clip (videoStartAsset).
Here is the code I'm using:
var mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: videoStartTimeRange.duration)
var videoLayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack)
var videoAssetTrack = videoStartAsset.tracksWithMediaType(AVMediaTypeVideo)[0] as AVAssetTrack
videoLayerInstruction.setOpacity(0.0, atTime: videoStartTimeRange.duration)
mainInstruction.layerInstructions = [videoLayerInstruction]
var mainCompositionInst = AVMutableVideoComposition()
var naturalSize = videoAssetTrack.naturalSize
var renderWidth = naturalSize.width
var renderHeight = naturalSize.height
mainCompositionInst.renderScale = Float(UIScreen.mainScreen().scale)
mainCompositionInst.renderSize = CGSize(width: 640.0, height: 480.0)
mainCompositionInst.instructions = [mainInstruction]
mainCompositionInst.frameDuration = CMTimeMake(1, 30)
var nameTextLayer = CATextLayer()
nameTextLayer.font = "FONT"
nameTextLayer.fontSize = 100
nameTextLayer.frame = CGRect(x: 0.0, y: 0.0, width: naturalSize.width, height: naturalSize.height)
if let nameText = nameInputText?.label?.text {
nameTextLayer.string = "TEXT"
} else {
nameTextLayer.string = "DEFAULT TEXT"
}
nameTextLayer.alignmentMode = kCAAlignmentCenter
nameTextLayer.foregroundColor = UIColor.whiteColor().CGColor
var overlayLayer = CALayer()
overlayLayer.addSublayer(nameTextLayer)
overlayLayer.frame = CGRect(x: 0.0, y: 0.0, width: naturalSize.width, height: naturalSize.height)
overlayLayer.masksToBounds = true
var parentLayer = CALayer()
var videoLayer = CALayer()
parentLayer.frame = CGRect(x: 0.0, y: 0.0, width: naturalSize.width, height: naturalSize.height)
videoLayer.frame = CGRect(x: 0.0, y: 0.0, width: naturalSize.width, height: naturalSize.height)
parentLayer.addSublayer(videoLayer)
parentLayer.addSublayer(overlayLayer)
mainCompositionInst.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, inLayer: parentLayer)
Thanks.
Fixed my own problem; turns out the error was being thrown because of the following line:
mainInstruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: videoStartTimeRange.duration)
This is because I am setting the timeRange to be the time range of the first video clip (where the text should be added), instead of the timeRange of the entire video (I am combining 3 videos into one, so I needed to set the timeRange to be the sum of all their durations).
Thank you Apple for the very descriptive error message. /sarcasm