尝试将 CATextLayer 添加到视频时出现无效合成错误 (-11841)

Invalid composition error (-11841) when trying to add CATextLayer to video

我正在尝试在视频上添加文本,但无论我做什么,我都会收到无效合成错误 (-11841)。我遵循了教程,通读了线程,没有发现任何错误。我正在组合 3 个视频和一个音轨,效果很好。我正在尝试在第一个视频剪辑 (videoStartAsset) 的持续时间内添加文本。

这是我使用的代码:

   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)

谢谢。

AVErrorInvalidVideoComposition = -11841,

You attempted to perform a video composition operation that is not supported.

Available in iOS 5.0 and later.

您可以找到有关 AVFoundation 错误的更多信息 here

解决了我自己的问题;结果是由于以下行而引发错误:

mainInstruction.timeRange = CMTimeRange(start: kCMTimeZero, duration: videoStartTimeRange.duration)

这是因为我将timeRange设置为第一个视频剪辑的时间范围(应该添加文本的地方),而不是整个视频的timeRange(我将3个视频合并为一个,所以我需要将 timeRange 设置为它们所有持续时间的总和)。

感谢 Apple 提供非常详细的错误消息。 /讽刺