我通过每 0.01 秒后捕获带有渲染上下文的屏幕图像来创建视频。具有透明背景的捕获图像。但是当使用 AVAssetWritter、AVAssetWriterInputPixelBufferAdaptor 用这些图像创建视频时,它的透明背景会变成黑色。
我正在使用以下代码:-
canvasAssetWriter = [[AVAssetWriter alloc] initWithURL:[self tempFileURL:@"output.mp4"] fileType:AVFileTypeQuickTimeMovie error:&error];
NSParameterAssert(canvasAssetWriter);
//Configure video
NSDictionary* videoCompressionProps = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:1024.0*1024.0], AVVideoAverageBitRateKey,
nil ];
NSLog(@"System Version : %f WindowWidth : %f, windowHeight : %f",kSystemVersion,kWindowWidth,kWindowHeight);
NSDictionary* videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:(kSystemVersion < 8.0)?kWindowHeight:kWindowWidth], AVVideoWidthKey,
[NSNumber numberWithInt:(kSystemVersion < 8.0)?kWindowWidth:kWindowHeight], AVVideoHeightKey,
videoCompressionProps, AVVideoCompressionPropertiesKey,
nil];
canvasVideoAssetWriterInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings] retain];
NSParameterAssert(canvasVideoAssetWriterInput);
canvasVideoAssetWriterInput.expectsMediaDataInRealTime = NO;
NSDictionary* bufferAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kCMPixelFormat_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];
avAdaptor = [[AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:canvasVideoAssetWriterInput sourcePixelBufferAttributes:bufferAttributes] retain];
//add input
[canvasAssetWriter addInput:canvasVideoAssetWriterInput];
[canvasAssetWriter startWriting];
[canvasAssetWriter startSessionAtSourceTime:CMTimeMake(0, 1000)];
CVPixelBufferRef pixelBuffer = NULL; CGImageRef cgImage = CGImageCreateCopy([capturedImage CGImage]);
CFDataRef image = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
pixelBuffer = [self pixelBufferFasterWithImage:cgImage];
if(pixelBuffer !=nil)
{
// set image data into pixel buffer
CVPixelBufferLockBaseAddress( pixelBuffer, 0 );
uint8_t* destPixels = CVPixelBufferGetBaseAddress(pixelBuffer);
CFDataGetBytes(image, CFRangeMake(0, CFDataGetLength(image)), destPixels); //XXX: will work if the pixel buffer is contiguous and has the same bytesPerRow as the input data
BOOL success = [avAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:time];