我正在尝试使用AVFoundation裁剪我正在录制的视频。所以我想创建一个AVCaptureVideoPreviewLayer并将帧设置为300x300。
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
captureVideoPreviewLayer.delegate = self;
captureVideoPreviewLayer.frame = CGRectMake(0,0, 300, 300);
[previewView.layer addSublayer:captureVideoPreviewLayer];
用户看到视频被裁剪。我想完全按照用户查看的方式保存视频。使用AVCaptureMovieFileOutput,视频显然可以保存而不会裁剪。我正在考虑使用AVCaptureVideoDataOutput截取帧并自己裁剪它们,但我想知道是否有更有效的方法来实现这一点,可能是使用AVExportSession并使用AVVideoComposition。
任何指导都将不胜感激。
答案 0 :(得分:28)
像这样的东西。 99%的代码只是将其设置为自定义CGAffineTransform,然后保存结果。
我假设您希望裁剪的视频占据输出的完整大小/宽度 - 例如,缩放仿射是正确的解决方案(放大视频,产生裁剪+调整大小的效果)。
AVAsset* asset = // your input
AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
AVMutableVideoComposition* videoComposition = [[AVMutableVideoComposition videoComposition]retain];
videoComposition.renderSize = CGSizeMake(320, 240);
videoComposition.frameDuration = CMTimeMake(1, 30);
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30) );
AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack];
CGAffineTransform finalTransform = // setup a transform that grows the video, effectively causing a crop
[transformer setTransform:finalTransform atTime:kCMTimeZero];
instruction.layerInstructions = [NSArray arrayWithObject:transformer];
videoComposition.instructions = [NSArray arrayWithObject: instruction];
exporter = [[AVAssetExportSession alloc] initWithAsset:saveComposition presetName:AVAssetExportPresetHighestQuality] ;
exporter.videoComposition = videoComposition;
exporter.outputURL=url3;
exporter.outputFileType=AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^(void){}];
答案 1 :(得分:10)
ios7添加了一个特定的Layer指令,仅用于裁剪。
videolayerInstruction setCropRectangle:atTime:
_mike