- (void)saveVideo:(NSMutableArray *)imageArr withPaths:(NSString *)paths andCallBack:(void(^)(void))callBack
{
if (!imageArr.count) {
return;
}
UIImage *image = self.screenCap;
CGSize sizeImage = image.size;
int width = ((int) (sizeImage.width / 16) * 16);
int height = ((int) (sizeImage.height / 16) * 16);
NSLog(@"%d,%d",width,height);
CGSize size = CGSizeMake(width, height);
NSError *error = nil;
unlink([paths UTF8String]);
AVAssetWriter *videoWriter = [[AVAssetWriter alloc] initWithURL:
[NSURL fileURLWithPath:paths]
fileType:AVFileTypeQuickTimeMovie
error:&error];
NSParameterAssert(videoWriter);
if(error)
NSLog(@"error = %@", [error localizedDescription]);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:size.width], AVVideoWidthKey,
[NSNumber numberWithInt:size.height], AVVideoHeightKey, nil];
AVAssetWriterInput *writerInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];
NSDictionary *sourcePixelBufferAttributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:kCVPixelFormatType_32ARGB], kCVPixelBufferPixelFormatTypeKey, nil];
AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor assetWriterInputPixelBufferAdaptorWithAssetWriterInput:writerInput
sourcePixelBufferAttributes:sourcePixelBufferAttributesDictionary];
NSParameterAssert(writerInput);
NSParameterAssert([videoWriter canAddInput:writerInput]);
if ([videoWriter canAddInput:writerInput])
NSLog(@"I can add this input");
else
NSLog(@"i can't add this input");
[videoWriter addInput:writerInput];
[videoWriter startWriting];
[videoWriter startSessionAtSourceTime:kCMTimeZero];
dispatch_queue_t dispatchQueue = dispatch_queue_create("mediaInputQueue", NULL);
[writerInput requestMediaDataWhenReadyOnQueue:dispatchQueue usingBlock:^{
CVPixelBufferRef buffer = NULL;
NSUInteger fps = 10;
int frameCount = 0;
double numberOfSecondsPerFrame = 0.1;
double frameDuration = fps * numberOfSecondsPerFrame;
for (UIImage *img in imageArr)
{
buffer = [self pixelBufferFromCGImage:[img CGImage] size:size];
BOOL append_ok = NO;
int j = 0;
while (!append_ok && j < 30)
{
if (adaptor.assetWriterInput.readyForMoreMediaData)
{
CMTime frameTime = CMTimeMake(frameCount * frameDuration, (int32_t) fps);
append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
if (!append_ok)
{
NSError *error = videoWriter.error;
if (error != nil)
{
NSLog(@"Unresolved error %@,%@.", error, [error userInfo]);
}
}
}
else
{
printf("adaptor not ready %d, %d\n", frameCount, j);
[NSThread sleepForTimeInterval:0.1];
}
j++;
}
if (!append_ok)
{
printf("error appending image %d times %d\n, with error.", frameCount, j);
}
frameCount++;
CVPixelBufferRelease(buffer);
}
[writerInput markAsFinished];
[videoWriter finishWriting];
callBack();
}];
NSLog(@"outside for loop");
}