我已经阅读了文档和相关问题,似乎没有一个可以帮助我解决问题。我尝试使用AVAssetWriter从单个静止图像创建* .mp4文件。
我无法使用finishWritingWithCompletionHandler获取资产来调用它的完成块:
我对AVAssetWriter对象保持强烈的引用。
任何帮助或见解都将不胜感激。
- (void)videoFromImage:(UIImage *)image
{
NSError *error;
self.videoWriter = [[AVAssetWriter alloc] initWithURL:
[NSURL fileURLWithPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"output.mp4"]] fileType:AVFileTypeQuickTimeMovie
error:&error];
if (!error) {
NSParameterAssert(self.videoWriter);
NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:image.size.width], AVVideoWidthKey,
[NSNumber numberWithInt:image.size.height], AVVideoHeightKey,
nil];
AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput
assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:videoSettings];
AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
sourcePixelBufferAttributes:nil];
NSParameterAssert(videoWriterInput);
NSParameterAssert([self.videoWriter canAddInput:videoWriterInput]);
[self.videoWriter addInput:videoWriterInput];
[self.videoWriter startWriting];
[self.videoWriter startSessionAtSourceTime:kCMTimeZero];
if (adaptor.assetWriterInput.readyForMoreMediaData) {
CVPixelBufferRef buffer = [self pixelBufferFromImage:image];
[adaptor appendPixelBuffer:buffer withPresentationTime:kCMTimeZero];
}
[videoWriterInput markAsFinished];
[self.videoWriter finishWritingWithCompletionHandler:^{
NSLog(@"finished"); // Never gets called
}];
}
else {
NSLog(@"%@", error.localizedDescription);
}
}
编辑:AVAssetWriter无法写入文件,因为已存在同名文件。加入
NSFileManager *manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"output.mp4"]]) {
NSError *fileError;
[manager removeItemAtPath:[[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"output.mp4"] error:&fileError];
if (fileError) NSLog(@"%@", fileError.localizedDescription);
}
它完美无缺。