在视频文字中添加水印不会显示

时间:2017-03-08 19:26:40

标签: ios swift3 avfoundation

我是Swift的新手。我正在制作一个应用程序,可以为视频添加自定义动画和效果,如水印。我写了这段代码来添加水印。问题是显示水印矩形并显示图像但未显示文本。这是代码

let videoAsset = AVURLAsset(url: URL(fileURLWithPath: path!))
    let mixComposition: AVMutableComposition = AVMutableComposition()
    let mutableTrack = mixComposition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: kCMPersistentTrackID_Invalid)

    let assetTrack = videoAsset.tracks(withMediaType: AVMediaTypeVideo)[0]
    let timeRangeForVideoAsset = CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
    print("1 ...")
    do{
        try mutableTrack.insertTimeRange(timeRangeForVideoAsset, of: assetTrack, at: kCMTimeZero)
    }catch{
        print("Error in adding time range")
    }
    mutableTrack.preferredTransform = assetTrack.preferredTransform

    let imageLayer: CALayer = CALayer()
    var im = Bundle.main.path(forResource: "Ground", ofType: "png")
    let image = UIImage(contentsOfFile: im!)
    print("2 ...")
    imageLayer.contents = image?.cgImage
    imageLayer.opacity = 0.7
    imageLayer.frame = CGRect(x: 0, y: 100, width: self.view.frame.width, height: 50)

    let videoSize = assetTrack.naturalSize
    let parentLayer = CALayer()
    let videoLayer = CALayer()

    parentLayer.frame = CGRect(x: 0, y: 0, width: assetTrack.naturalSize.width, height: assetTrack.naturalSize.height)
    videoLayer.frame = CGRect(x: 0, y: 0, width: assetTrack.naturalSize.width, height: assetTrack.naturalSize.height)
    print("3 ...")

    let titleLayer = CATextLayer()
    titleLayer.backgroundColor = UIColor.white.cgColor
    titleLayer.string = "Dummy text"
    titleLayer.foregroundColor = UIColor.black.cgColor
    titleLayer.font = UIFont(name: "Helvetica", size: 28)
    titleLayer.opacity = 1.0
    titleLayer.shadowOpacity = 0.5
    titleLayer.alignmentMode = kCAAlignmentCenter
    titleLayer.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 50)
    parentLayer.addSublayer(videoLayer)
    parentLayer.addSublayer(imageLayer)
    parentLayer.addSublayer(titleLayer)

    let videoComp = AVMutableVideoComposition()
    videoComp.renderSize = videoSize
    videoComp.frameDuration = CMTimeMake(1, 30)
    videoComp.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: parentLayer)
    print("4 ...")
    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, mixComposition.duration)
    var layerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: assetTrack)
    instruction.layerInstructions = [layerInstruction]
    videoComp.instructions = [instruction]
    print("5 ...")
    let assetExport = AVAssetExportSession(asset: mixComposition, presetName: AVAssetExportPresetHighestQuality)
    assetExport?.videoComposition = videoComp
    let videoName = "markedVideo.mov"
    var exPath = NSTemporaryDirectory().appending(videoName)
    if(FileManager.default.fileExists(atPath: exPath)){
        do{
            try FileManager.default.removeItem(atPath: exPath)
        }
        catch{
            print("File Not Deleted")
        }
    }
    print("6 ...")
    assetExport?.outputFileType = AVFileTypeQuickTimeMovie
    assetExport?.outputURL = URL(fileURLWithPath: exPath)
    assetExport?.shouldOptimizeForNetworkUse = true
    assetExport?.exportAsynchronously(completionHandler: {
        print("Success ...")
        self.playWithMPKit(path: exPath)
    })

请帮助我,我做错了什么。我会感激你的。

1 个答案:

答案 0 :(得分:1)

我在制作自己的应用程序时注意到了这个问题

我的应用程序的一部分功能是在我的视频中添加字幕我尝试使用 CATextLayer 将我的字幕渲染到我的AVMutableComposition obj.但我也失败了 然后我尝试使用容器作为桥梁。所以我将 CATextLayer 放入 CALayer ,然后将此 CALayer 添加到animationTool's子层。

let subtitle = CATextLayer()
/*
   setup subtitle's properties...
*/
let subtitle_container = CALayer()
/*
   setup container's frame/position/rotation/animations<-(such as subtitles fade in / out effects)...
*/
subtitle_container.addSublayer(subtitle)
parentLayer.addSublayer(subtitle_container)

在我的应用程序中,这将起到作用,但是没有渲染CATextLayer的原因,仍然不知道为什么。

希望可以提供帮助

更新21/3/2017

这是我项目中的一些代码,我使用的是OC而不是swift。

        RAGE_SubtitleModel * m = subtitleModelArray[i];
        // ^this model contained the frame of subtitle, start time , end time.

        CGFloat subtitle_startTime = CMTimeGetSeconds(m.timeMapping.target.start);
        CGFloat subtitle_duration  = CMTimeGetSeconds(m.timeMapping.target.duration);

        CALayer * subtitle_container = [CALayer layer];
        CATextLayer * subtitle_layer = [CATextLayer layer];
        //  Font
        [subtitle_layer setFont:(__bridge CFTypeRef _Nullable)(m.font.fontName)];
        //  Font Size
        [subtitle_layer setFontSize:m.fontSize * MAX(ratioW, ratioH)];
        //  Background Color
        [subtitle_layer setBackgroundColor:[UIColor clearColor].CGColor];
        //  Subtitle Color
        [subtitle_layer setForegroundColor:m.color.CGColor];
        //  Subtitle Content
        [subtitle_layer setString:m.string];
        //  Subtitle Alignment Type
        [subtitle_layer setAlignmentMode:kCAAlignmentLeft];

        [subtitle_layer setContentsScale:SCREEN_SCALE];
        //  Subtitle Position
        [subtitle_container setFrame:CGRectMake(0,
                                                 0,
                                                targetSize.width,
                                                targetSize.height)];

        [subtitle_layer setFrame:CGRectMake(0, 0, m.frame.size.width * ratioW, m.frame.size.height * ratioH)];

        [subtitle_layer setAnchorPoint:CGPointMake(.5,.5)];

        [subtitle_layer setPosition:CGPointMake(m.frame.origin.x * ratioW + m.frame.size.width * ratioW * .5f,
                                                targetSize.height - m.frame.origin.y * ratioH - m.frame.size.height * ratioH * .5f)];

        [subtitle_container addSublayer:subtitle_layer];
        [renderingLayer addSublayer:subtitle_container];

如上所述,我使用subtitle_container,我提到CALayer,并将容器添加到renderingLayer parentLayer

这是可能的,因为你的水印框架不正确,所以你只渲染容器?我正在设置容器的宽度和宽度。高度到我的输出视频的宽度&amp;高度,所以我有一个全屏容器,之后,调整我的CATextLayer变得更容易。

对你有用吗?