如何使用CATextLayer为视频添加字幕

时间:2014-05-08 18:07:46

标签: objective-c

我试图为我用我的应用程序捕获的视频添加字幕,但我无法知道如何做到这一点。到目前为止,我只能使用以下代码为整个视频添加一个字符串:

CATextLayer *aLayer = [CATextLayer layer];
aLayer.frame = CGRectMake(0, 0, 320, 480);
aLayer.bounds = CGRectMake(0, 0, 320, 480);
aLayer.string = @"Text goes here";
aLayer.backgroundColor = [UIColor clearColor].CGColor;
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:urlVideo options:nil];

self.cmp = [AVMutableComposition composition];
AVMutableCompositionTrack *trackA = [self.cmp addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *sourceVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
[trackA insertTimeRange:CMTimeRangeMake(kCMTimeZero, [asset duration]) ofTrack:sourceVideoTrack atTime:kCMTimeZero error:nil] ;

self.animComp = [AVMutableVideoComposition videoComposition];
self.animComp.renderSize = CGSizeMake(640, 480);
self.animComp.frameDuration = CMTimeMake(1,30);

CALayer *parentLayer = [CALayer layer];
CALayer *videoLayer = [CALayer layer];
parentLayer.frame = CGRectMake(0, 0, 640, 480);
videoLayer.frame = CGRectMake(0, 0, 640, 480);
[parentLayer addSublayer:videoLayer];
[parentLayer addSublayer:aLayer];

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

AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, [asset duration]);
AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:trackA];

[layerInstruction setOpacity:1.0 atTime:kCMTimeZero];
instruction.layerInstructions = [NSArray arrayWithObject:layerInstruction] ;
self.animComp.instructions = [NSArray arrayWithObject:instruction];
[self exportMovie:self];

更具体地说,我想在电影的某些帧中添加一些字符串。

1 个答案:

答案 0 :(得分:1)

这不是一个确切的答案,但您可以使用CAMediaTimingFunction,也可以使用代码中的部分,您可以使用kCMTimeZero设置字幕的计时器。您可以通过更改要添加的每个字符串的kCMTimer值来为您添加的字符串添加计时器,以便添加字幕。