iOS :视频嵌入srt字幕方式二

在AVFoundation框架中的AVMutableVideoComposition加载字幕图层:

核心代码:
根据时间节点在videoLayer上插入多个CATextLayer
CATextLayer默认是透明的,需要使用动画在对应的时间节点上显示CATextLayer,对它们设置透明度1.0,这样就能生成一个带字幕的视频了。
相比使用AVAssetReader+AVAssetWriter,这种方式代码简单,不需要考虑内存泄漏,相比使用AVAssetRead+AVAssetWriter方式性能提升很多

+ (void)addSubtitles:(NSArray*)subtitles naturalSize:(CGSize)naturalSize mainCompositionInst:(AVMutableVideoComposition*)mainCompositionInst{
    CALayer *parentLayer = [CALayer layer];
    CALayer *videoLayer = [CALayer layer];
    parentLayer.frame = CGRectMake(0, 0, naturalSize.width, naturalSize.height);
    videoLayer.frame = CGRectMake(0, 0, naturalSize.width, naturalSize.height);
    [parentLayer addSublayer:videoLayer];
    
    //开始添加字幕图层
    [subtitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        float begin = [subtitles[idx][@"begin"] floatValue];
        float end = [subtitles[idx][@"end"] floatValue];
        NSString* subtitle = subtitles[idx][@"subtitle"];
        
        CATextLayer * textLayer = [CATextLayer layer];
        textLayer.opacity = 0;//优先透明
        textLayer.backgroundColor = [UIColor redColor].CGColor;
        textLayer.string = subtitle;
        textLayer.frame = CGRectMake(0, 0, naturalSize.width, 80);
        textLayer.alignmentMode = kCAAlignmentCenter;
        //添加动画
        [textLayer addAnimation:[ccSubtitleComposition addAnimationWithBegin:begin end:end] forKey:@"animateOpacity"];
        [parentLayer addSublayer:textLayer];
        mainCompositionInst.animationTool = [AVVideoCompositionCoreAnimationTool
                                             videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    }];
}

GitHub:
https://github.com/qw9685/srt-2-.git

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容