如何在iOS SDK中为视频的某段时间添加文本

时间:2017-02-17 05:15:35

标签: ios video avassetexportsession

我的视频持续时间为4:00。现在我想根据视频帧在视频文件中添加文本。例如,从00:30到1:50持续时间我要添加文字"欢迎"。现在从3:00到4:00视频的持续时间,我想添加文字" Awesome"。如何实现这一功能。我在下面的教程中提到过。它在整个视频中添加文本而不是视频的一段时间。 https://www.raywenderlich.com/30200/avfoundation-tutorial-adding-overlays-and-animations-to-videos

任何帮助都会得到满足。

我在整个视频中添加了添加文字的代码行:

- (void)applyVideoEffectsToComposition:(AVMutableVideoComposition *)composition size:(CGSize)size
{
    // 1 - Set up the text layer
    CATextLayer *subtitle1Text = [[CATextLayer alloc] init];
    [subtitle1Text setFont:@"Helvetica-Bold"];
    [subtitle1Text setFontSize:36];
    [subtitle1Text setFrame:CGRectMake(0, 0, size.width, 100)];
    [subtitle1Text setString:_subTitle1.text];
    [subtitle1Text setAlignmentMode:kCAAlignmentCenter];
    [subtitle1Text setForegroundColor:[[UIColor whiteColor] CGColor]];

    // 2 - The usual overlay
    CALayer *overlayLayer = [CALayer layer];
    [overlayLayer addSublayer:subtitle1Text];
    overlayLayer.frame = CGRectMake(0, 0, size.width, size.height);
    [overlayLayer setMasksToBounds:YES];

    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, size.width, size.height);
    videoLayer.frame = CGRectMake(0, 0, size.width, size.height);
    [parentLayer addSublayer:videoLayer];
    [parentLayer addSublayer:overlayLayer];

    composition.animationTool = [AVVideoCompositionCoreAnimationTool
                                 videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];

}

2 个答案:

答案 0 :(得分:0)

编辑answer是否适合您?您必须添加多个文本图层,并使用CABasicAnimation在适当的时间显示/隐藏每个图层(使用setBeginTime:)。

原始答案 基本上,只需在此部分代码中维护对CATextLayer的引用,并使用每秒调用一次的NSTimer来更新文本:

// 1 - Set up the text layer
CATextLayer *subtitle1Text = [[CATextLayer alloc] init]; 
self.textLayer = subtitle1Text; // ### Keep a reference to this object and update it in timerDidFire
...

- (void)viewDidLoad{
    ...
    // Add a timer at some point.  Don't forget to invalidate it later
    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerDidFire) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    ...
}

- (void)timerDidFire{
    if (currentPlaybackPosition <= some_value){
        [self.textLayer setText:@"Welcome"];
    } else if (currentPlaybackPosition <= some_bigger_value){
        [self.textLayer setText:@"Awesome"];
    }
    ...
}

答案 1 :(得分:0)

查看您关联的网站:https://www.raywenderlich.com/30200/avfoundation-tutorial-adding-overlays-and-animations-to-videos 只需使用2个CATextLayer,如图所示。设置他们的文本。

将第一个beginTime属性设置为30秒,将其duration属性设置为80秒。第二个,beginTime为180秒,duration为60秒。

结果将在视频播放器中显示时导出。