AvAssetReader 和 Writer 用于叠加视频



我正在尝试用AvAssetReader和AvAssetWriter覆盖录制的视频与一些图像。按照本教程,我能够将视频(和音频)复制到新文件中。现在我的目标是使用以下代码将一些初始视频帧与一些图像覆盖:

while ([assetWriterVideoInput isReadyForMoreMediaData] && !completedOrFailed)
            {
                // Get the next video sample buffer, and append it to the output file.
                CMSampleBufferRef sampleBuffer = [assetReaderVideoOutput copyNextSampleBuffer];
                CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
                CVPixelBufferLockBaseAddress(pixelBuffer, 0);
                EAGLContext *eaglContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
                CIContext *ciContext = [CIContext contextWithEAGLContext:eaglContext options:@{kCIContextWorkingColorSpace : [NSNull null]}];
                UIFont *font = [UIFont fontWithName:@"Helvetica" size:40];
                NSDictionary *attributes = @{NSFontAttributeName:font, NSForegroundColorAttributeName:[UIColor lightTextColor]};
                UIImage *img = [self imageFromText:@"test" :attributes];
                CIImage *filteredImage = [[CIImage alloc] initWithCGImage:img.CGImage];
                [ciContext render:filteredImage toCVPixelBuffer:pixelBuffer bounds:[filteredImage extent] colorSpace:CGColorSpaceCreateDeviceRGB()];

                CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
                if (sampleBuffer != NULL)
                {
                    BOOL success = [assetWriterVideoInput appendSampleBuffer:sampleBuffer];
                    CFRelease(sampleBuffer);
                    sampleBuffer = NULL;
                    completedOrFailed = !success;
                }
                else
                {
                    completedOrFailed = YES;
                }
            }

要从文本创建图像:

-(UIImage *)imageFromText:(NSString *)text :(NSDictionary *)attributes{
CGSize size = [text sizeWithAttributes:attributes];
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
[text drawAtPoint:CGPointMake(0.0, 0.0) withAttributes:attributes];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}

视频和音频被复制,但我的视频上没有任何文本。

问题 1:为什么此代码不起作用?

此外,我希望能够检查当前读取帧的时间码。例如,我想在视频中插入带有当前时间码的文本。

我按照本教程尝试此代码:

        AVAsset *localAsset = [AVAsset assetWithURL:mURL];
    NSError *localError;
    AVAssetReader *assetReader = [[AVAssetReader alloc] initWithAsset:localAsset error:&localError];
    BOOL success = (assetReader != nil);
    // Create asset reader output for the first timecode track of the asset
    if (success) {
        AVAssetTrack *timecodeTrack = nil;
        // Grab first timecode track, if the asset has them
        NSArray *timecodeTracks = [localAsset tracksWithMediaType:AVMediaTypeTimecode];
        if ([timecodeTracks count] > 0)
            timecodeTrack = [timecodeTracks objectAtIndex:0];
        if (timecodeTrack) {
            AVAssetReaderTrackOutput *timecodeOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:timecodeTrack outputSettings:nil];
            [assetReader addOutput:timecodeOutput];
        } else {
            NSLog(@"%@ has no timecode tracks", localAsset);
        }
    }

但我得到日志:

[...] 没有时间码轨道

问题2:为什么我的视频没有任何AVMediaTypeTimecode?广告那么如何获取当前帧时间码呢?

感谢您的帮助

我找到了解决方案:

要叠加视频帧,您需要修复解压缩设置:

NSString* key = (NSString*)kCVPixelBufferPixelFormatTypeKey;
NSNumber* value = [NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA];
NSDictionary* decompressionVideoSettings = [NSDictionary dictionaryWithObject:value forKey:key];
// If there is a video track to read, set the decompression settings for YUV and create the asset reader output.
assetReaderVideoOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:assetVideoTrack outputSettings:decompressionVideoSettings];

要获取帧时间戳,您必须读取视频信息,然后使用计数器递增当前时间戳:

durationSeconds = CMTimeGetSeconds(asset.duration);
timePerFrame = 1.0 / (Float64)assetVideoTrack.nominalFrameRate;
totalFrames = durationSeconds * assetVideoTrack.nominalFrameRate;

然后在这个循环中

while ([assetWriterVideoInput isReadyForMoreMediaData] && !completeOrFailed)

您可以找到时间戳:

CMSampleBufferRef sampleBuffer = [assetReaderVideoOutput copyNextSampleBuffer];
if (sampleBuffer != NULL){
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
if (pixelBuffer) {
Float64 secondsIn = ((float)counter/totalFrames)*durationSeconds;
CMTime imageTimeEstimate = CMTimeMakeWithSeconds(secondsIn, 600);
mergeTime = CMTimeGetSeconds(imageTimeEstimate);
                                    counter++;
}
}

我希望它能有所帮助!

最新更新