在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];
}];
}