我想在 MPMoviePlayerViewController 正在播放的视频上添加一个文本或字符串,使其成为正在播放的视频的一部分。因此,当我在 Facebook 或 Twitter 上发布该视频时,文本必须显示在视频上方。
为此,我尝试获取视频的所有帧,然后在每个帧上写入文本,然后再次制作所有这些帧的视频。但是这样,我遇到了内存问题,它在设备上崩溃了。
- (NSArray*)getVideoFramesFromMovieController:(MPMoviePlayerViewController*)mpMoviePlayerVC
{ NSLog(@"Getting frames from a video asset.");
// videoFrames = [NSMutableArray array];
NSMutableArray *videoFrames = [NSMutableArray array];
for(float i= 0; i <= mpMoviePlayerVC.moviePlayer.duration; )
{
UIImage *singleFrameImage = [mpMoviePlayerVC.moviePlayer thumbnailImageAtTime:i timeOption:MPMovieTimeOptionExact];
[videoFrames addObject:singleFrameImage];
NSLog(@"Got frame number : %d",[videoFrames count]);
i = i + (1/self.frameRate) ; //frame capturing duration i.e. 15fps //self.frameRate
}
NSLog(@"Total frames: %d",[videoFrames count]);
return [NSArray arrayWithArray:videoFrames];
}
上面的方法给了我所有的帧,我在所有这些文本上写了一个文本,说“你好”,然后制作所有这些帧的视频。
-(void)writeImageAsMovie:(NSArray *)array toPath:(NSString*)path size:(CGSize)size
{
NSLog(@"Inside writeImageAsMovie method.");
NSError *error = nil;
AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
[NSURL fileURLWithPath:path] fileType:AVFileTypeMPEG4
error:&error];
NSParameterAssert(videoWriter);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:size.width], AVVideoWidthKey,
[NSNumber numberWithInt:size.height], AVVideoHeightKey,
nil];
AVAssetWriterInput* writerInput = [[AVAssetWriterInput
assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:videoSettings] retain];
AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
sourcePixelBufferAttributes:nil];
NSParameterAssert(writerInput);
NSParameterAssert([videoWriter canAddInput:writerInput]);
[videoWriter addInput:writerInput];
//Start a session:
[videoWriter startWriting];
[videoWriter startSessionAtSourceTime:kCMTimeZero];
dispatch_queue_t dispatchQueue = dispatch_queue_create("mediaInputQueue", NULL);
int __block frame = 0;
[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
while ([writerInput isReadyForMoreMediaData])
{
NSLog(@"Total frames to be written: %d",[array count]);
if(++frame >= [array count]) //total frames
{
[writerInput markAsFinished];
[videoWriter finishWriting];
[videoWriter release];
break;
}
CVPixelBufferRef buffer = (CVPixelBufferRef)[self pixelBufferFromCGImage:[[array objectAtIndex:frame]CGImage] andSize:size];
if (buffer)
{
if(![adaptor appendPixelBuffer:buffer withPresentationTime:CMTimeMake(frame, self.frameRate)])
NSLog(@"FAIL");
else
NSLog(@"Success:%d", frame);
CFRelease(buffer);
}
}
}];
NSLog(@"outside for loop");
[self performSelector:@selector(waitTillVideoFinishes) withObject:nil afterDelay:20.0];
}
它在 mac 上运行良好,但由于内存问题而在设备上崩溃。
我还尝试了各种方法来为视频上的文字添加水印,但无法通过。提前致谢。