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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 什么是 AVFoundationAVFoundation是苹果公司提供的一个多媒体处理框架,它能够处理音频、视频、文本和图像等媒体类型,还能够实现录制、编辑、播放等多种操作。 2. AVFoundation的优点是什么? AVFoundation有以下几个优点: - 它可以在多个平台上使用,包括iOS、macOS和tvOS等。 - 它提供了灵活的API,可以对多种媒体类型进行处理。 - 它支持硬件加速,能够提高处理速度和性能。 - 它支持多种格式的媒体文件,包括MP3、AAC、H.264和MPEG-4等。 3. 如何使用AVFoundation实现音频录制? 在使用AVFoundation实现音频录制时,需要执行以下步骤: - 创建一个AVAudioSession对象,用于管理音频会话。 - 创建一个AVAudioRecorder对象,用于录制音频。 - 配置录音参数,例如音频格式、采样率、通道数、音频质量等。 - 调用AVAudioRecorder的record方法开始录音。 - 调用AVAudioRecorder的stop方法停止录音。 4. AVFoundation中的AVPlayerLayer是什么? AVPlayerLayer是一个CALayer子类,用于在iOS和macOS应用程序中显示视频内容。它可以显示一个AVPlayer对象的输出,并且支持全屏播放、画中画、视频内容缩放等功能。 5. 如何使用AVFoundation实现视频播放? 在使用AVFoundation实现视频播放时,需要执行以下步骤: - 创建一个AVPlayer对象,用于播放视频。 - 创建一个AVPlayerLayer对象,用于显示视频内容。 - 将AVPlayerLayer对象添加到视图层次结构中。 - 创建一个AVPlayerItem对象,用于管理视频资源。 - 调用AVPlayer的replaceCurrentItemWithPlayerItem方法将AVPlayerItem与AVPlayer关联。 - 调用AVPlayer的play方法开始播放视频。 6. 如何在AVFoundation中实现视频编辑? 在AVFoundation中实现视频编辑通常需要使用AVAsset、AVAssetTrack、AVComposition、AVMutableComposition等类。以下是实现视频编辑的大致步骤: - 创建一个AVAsset对象,用于表示视频资源。 - 创建一个AVMutableComposition对象,用于管理视频资源。 - 使用AVAssetTrack获取视频的音频和视频轨道。 - 使用AVMutableCompositionTrack将音频和视频轨道添加到AVMutableComposition中。 - 使用AVAssetExportSession导出编辑后的视频。 7. AVFoundation中的AVCaptureSession是什么? AVCaptureSession是用于管理视频和音频输入的会话对象。它可以管理多个输入设备(例如摄像头、麦克风等)并且可以将它们合并到单个输出中。使用AVCaptureSession可以方便地实现视频录制、视频流传输、实时视频分析等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值