IOS使用AVFoundation在视频上添加字幕以及控制字幕时间

Stella981
• 阅读 772

IOS在视频上添加字幕效果的基本思路是:

  1. 使用自定义的CATextLayer文字图层或者CAShapeLayer文字图层,添加到视频的Layer上创建用户自定义的字幕效果。这两者的区别是:CATextLayer支持设置简单的文字效果,包括文字的内容、字体、字号大小、对其方式、文字颜色、背景颜色等基本的属性;CAShapeLayer功能更强大,提供了CATextLayer没有的边框大小、边框颜色等设置,如果需要更高级的文字内容展示,需要使用CATextLayer配合UIBezierPath来定制自定义的文字内容。

  2. 通过设置Layer图层的动画来控制字幕的时间点和时间长度,这里有一个坑如果单独设置CATextLayer或者CAShapeLayer的动画不能控制开始的时间,需要额外添加一个CALayer图层,把文字图层CATextLayer或者CAShapeLayer添加到父CALayer图层中,在文字图层CATextLayer或者CAShapeLayer上设置开始的动画

    NSTimeInterval animatedInStartTime = startTime + initAnimationDuration;
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.fromValue = @0.0f;
    fadeInAnimation.toValue = @1.0f;
    fadeInAnimation.additive = NO;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.beginTime = animatedInStartTime;
    fadeInAnimation.duration = animationDuration;
    fadeInAnimation.autoreverses = NO;
    fadeInAnimation.fillMode = kCAFillModeBoth;
    [textLayer addAnimation:fadeInAnimation forKey:@"opacity"];
    

在父CALayer图层上设置结束的动画,这样设置才能实现用户自定义的时间点和时间长度

NSTimeInterval animatedOutStartTime = startTime + duration - animationDuration;
    CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutAnimation.fromValue = @1.0f;
    fadeOutAnimation.toValue = @0.0f;
    fadeOutAnimation.additive = NO;
    fadeOutAnimation.removedOnCompletion = NO;
    fadeOutAnimation.beginTime = animatedOutStartTime;
    fadeOutAnimation.duration = animationDuration;
    fadeOutAnimation.autoreverses = NO;
    fadeOutAnimation.fillMode = kCAFillModeBoth;
    [animatedTitleLayer addAnimation:fadeOutAnimation forKey:@"opacity"];

完整的代码

- (CALayer *)buildLayerbuildTxt:(NSString*)text
                       textSize:(CGFloat)textSize
                      textColor:(UIColor*)textColor
                    strokeColor:(UIColor*)strokeColor
                        opacity:(CGFloat)opacity
                       textRect:(CGRect)textRect
                       fontPath:(NSString*)fontPath
                     viewBounds:(CGSize)viewBounds
                      startTime:(NSTimeInterval)startTime
                       duration:(NSTimeInterval)duration
{
    if (!text || [text isEqualToString:@""])
    {
        return nil;
    }
    
    // Create a layer for the overall title animation.
    CALayer *animatedTitleLayer = [CALayer layer];
    
    // 1. Create a layer for the text of the title.
    CATextLayer *titleLayer = [CATextLayer layer];
    titleLayer.string = text;
    titleLayer.font = (__bridge CFTypeRef)(@"Helvetica");
    titleLayer.fontSize = textSize;
    titleLayer.alignmentMode = kCAAlignmentCenter;
    titleLayer.bounds = CGRectMake(0, 0, textRect.size.width, textRect.size.height);
    titleLayer.foregroundColor = textColor.CGColor;
    titleLayer.backgroundColor = [UIColor clearColor].CGColor;
    // [animatedTitleLayer addSublayer:titleLayer];
    
    // 添加文字以及边框效果
    UIFont *font = nil;
    if ((fontPath != nil) && (fontPath.length > 0)) {
        font = [[FLVideoEditFontManager sharedFLVideoEditFontManager] fontWithPath:fontPath size:textSize];
        titleLayer.font = CGFontCreateWithFontName((__bridge CFStringRef)font.fontName);
    }
    if (font == nil) {
        titleLayer.font = (__bridge CFTypeRef)(@"Helvetica");
    }
    
    UIBezierPath *path = nil;
    if (font) {
        path = [FLLayerBuilderTool createPathForText:text fontHeight:textSize fontName:(__bridge CFStringRef)(font.fontName)];
    }
    else
    {
        path = [FLLayerBuilderTool createPathForText:text fontHeight:textSize fontName:CFSTR("Helvetica")];
    }
    CGRect rectPath = CGPathGetBoundingBox(path.CGPath);
    CAShapeLayer *textLayer = [CAShapeLayer layer];
    textLayer.path = path.CGPath;
    textLayer.lineWidth = 1;
    if (strokeColor != nil) {
        textLayer.strokeColor = strokeColor.CGColor;
    }
    if (textColor != nil) {
        textLayer.fillColor = textColor.CGColor;
    }
    textLayer.lineJoin = kCALineJoinRound;
    textLayer.lineCap = kCALineCapRound;
    textLayer.geometryFlipped = NO;
    textLayer.opacity = opacity;
    textLayer.bounds = CGRectMake(0, 0, rectPath.size.width, textSize+10);
    [animatedTitleLayer addSublayer:textLayer];
    
    // 动画图层位置
    animatedTitleLayer.position = CGPointMake(textRect.origin.x+textRect.size.width/2, viewBounds.height - textRect.size.height/2 - textRect.origin.y);
    
    NSTimeInterval initAnimationDuration = 0.1f;
    NSTimeInterval animationDuration = 0.1f;
    
    // 3.显示动画
    NSTimeInterval animatedInStartTime = startTime + initAnimationDuration;
    CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeInAnimation.fromValue = @0.0f;
    fadeInAnimation.toValue = @1.0f;
    fadeInAnimation.additive = NO;
    fadeInAnimation.removedOnCompletion = NO;
    fadeInAnimation.beginTime = animatedInStartTime;
    fadeInAnimation.duration = animationDuration;
    fadeInAnimation.autoreverses = NO;
    fadeInAnimation.fillMode = kCAFillModeBoth;
    [textLayer addAnimation:fadeInAnimation forKey:@"opacity"];
    
    NSTimeInterval animatedOutStartTime = startTime + duration - animationDuration;
    CABasicAnimation *fadeOutAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    fadeOutAnimation.fromValue = @1.0f;
    fadeOutAnimation.toValue = @0.0f;
    fadeOutAnimation.additive = NO;
    fadeOutAnimation.removedOnCompletion = NO;
    fadeOutAnimation.beginTime = animatedOutStartTime;
    fadeOutAnimation.duration = animationDuration;
    fadeOutAnimation.autoreverses = NO;
    fadeOutAnimation.fillMode = kCAFillModeBoth;
    
    [animatedTitleLayer addAnimation:fadeOutAnimation forKey:@"opacity"];
    
    return animatedTitleLayer;
}

依赖的工具类FLLayerBuilderTool.m文件:

#import "FLLayerBuilderTool.h"
#import <CoreText/CoreText.h>

@implementation FLLayerBuilderTool


+ (UIBezierPath*) createPathForText:(NSString*)string fontHeight:(CGFloat)height fontName:(CFStringRef)fontName
{
    if ([string length] < 1)
        return nil;
    
    UIBezierPath *combinedGlyphsPath = nil;
    CGMutablePathRef letters = CGPathCreateMutable();
    
    CTFontRef font = CTFontCreateWithName(fontName, height, NULL);
    if (font == nil) {
        font = (__bridge CFTypeRef)(@"Helvetica");
    }
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                           (__bridge id)font, kCTFontAttributeName,
                           nil];
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:string
                                                                     attributes:attrs];
    CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)attrString);
    CFArrayRef runArray = CTLineGetGlyphRuns(line);
    
    // for each RUN
    for (CFIndex runIndex = 0; runIndex < CFArrayGetCount(runArray); runIndex++)
    {
        // Get FONT for this run
        CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex);
        CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName);
        
        // for each GLYPH in run
        for (CFIndex runGlyphIndex = 0; runGlyphIndex < CTRunGetGlyphCount(run); runGlyphIndex++)
        {
            // get Glyph & Glyph-data
            CFRange thisGlyphRange = CFRangeMake(runGlyphIndex, 1);
            CGGlyph glyph;
            CGPoint position;
            CTRunGetGlyphs(run, thisGlyphRange, &glyph);
            CTRunGetPositions(run, thisGlyphRange, &position);
            
            // Get PATH of outline
            {
                CGPathRef letter = CTFontCreatePathForGlyph(runFont, glyph, NULL);
                CGAffineTransform t = CGAffineTransformMakeTranslation(position.x, position.y);
                CGPathAddPath(letters, &t, letter);
                CGPathRelease(letter);
            }
        }
    }
    CFRelease(line);
    
    combinedGlyphsPath = [UIBezierPath bezierPath];
    [combinedGlyphsPath moveToPoint:CGPointZero];
    [combinedGlyphsPath appendPath:[UIBezierPath bezierPathWithCGPath:letters]];
    
    CGPathRelease(letters);
    CFRelease(font);
    
    if (attrString)
    {
        attrString = nil;
    }
    
    return combinedGlyphsPath;
}

@end

参考资料:
视频特效制作:如何给视频添加边框、水印、动画以及3D效果
视频特效制作2
AVFoundation Tutorial: Adding Overlays and Animations to Videos

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
子桓 子桓
1年前
视频字幕能转换成文字么?
视频字幕能转换成文字么?回答是肯定的哟,入手PremierePro2022forMac中文版轻松解决上述难题,PremierePro2022(pr2022)Mac一款专业的视频编辑软件,可以用于制作电影、电视节目和各种视频内容。以下是它的一些主要特点:1.
绣鸾 绣鸾
1年前
Camtasia 2023 for Mac(视频录制和剪辑软件)
是一款功能强大的屏幕录制和视频编辑软件,可以用于制作教育课程、演示文稿、培训视频等。它具有一系列工具和功能,包括屏幕录制、视频编辑、音频编辑、字幕、特效等,使用户可以轻松地创建高质量的视频内容。Camtasia2023的屏幕录制功能可以捕捉计算机屏幕上的任
绣鸾 绣鸾
1年前
Camtasia 2023 for Mac(视频录制和剪辑软件)
是一款功能强大的屏幕录制和视频编辑软件,可以用于制作教育课程、演示文稿、培训视频等。它具有一系列工具和功能,包括屏幕录制、视频编辑、音频编辑、字幕、特效等,使用户可以轻松地创建高质量的视频内容。Camtasia2023的屏幕录制功能可以捕捉计算机屏幕上的任
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
凿壁偷光 凿壁偷光
1年前
mac视频播放器Infuse for Mac
InfuseforMac是一款强大的mac视频播放器软件,可以在iPhone、iPad、AppleTV和Mac上观看几乎任何视频格式的美妙方式。无需转换文件!Infuse针对macOS11进行了优化,具有强大的流媒体选项、Trakt同步以及无与伦比的AirPlay和字幕支持。华丽的界面。精确控制。和如丝般流畅的播放。
公孙晃 公孙晃
1年前
屏幕录制、视频编辑工具:ScreenFlow for mac
使用ScreenFlow,您可以轻松地记录您的计算机屏幕上发生的任何内容,并添加音频,视频和图像以创建一个完整的视频。该软件还提供了许多高级功能,如视频剪辑,转场效果,动画和字幕等,使您能够创建专业水平的视频内容。