使用 AVAsset/AVCaptureSession 裁剪视频
Posted
技术标签:
【中文标题】使用 AVAsset/AVCaptureSession 裁剪视频【英文标题】:Cropping a video with AVAsset/AVCaptureSession 【发布时间】:2015-01-14 00:14:17 【问题描述】:我正在尝试将视频裁剪为正方形。我已经有一个生成矩形分辨率 .mov 文件的 AVCaptureSession 设置。所以我只是想用我找到的一些代码来裁剪它here。这是我的代码:
-(void)cropVideo:(NSURL*)videoURL
// input file
AVAsset* asset = [AVAsset assetWithURL:videoURL];
AVMutableComposition *composition = [AVMutableComposition composition];
[composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
// input clip
AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
// make it square
AVMutableVideoComposition* videoComposition = [AVMutableVideoComposition videoComposition];
videoComposition.renderSize = CGSizeMake(clipVideoTrack.naturalSize.height, clipVideoTrack.naturalSize.height);
videoComposition.frameDuration = CMTimeMake(1, 30);
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30) );
// rotate to portrait
AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack];
CGAffineTransform t1 = CGAffineTransformMakeTranslation(clipVideoTrack.naturalSize.height, -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) /2 );
CGAffineTransform t2 = CGAffineTransformRotate(t1, M_PI_2);
CGAffineTransform finalTransform = t2;
[transformer setTransform:finalTransform atTime:kCMTimeZero];
instruction.layerInstructions = [NSArray arrayWithObject:transformer];
videoComposition.instructions = [NSArray arrayWithObject: instruction];
// export
exporter = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality] ;
exporter.videoComposition = videoComposition;
NSURL *tmpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
NSURL *fileURL = [[tmpDirURL URLByAppendingPathComponent:@"final"] URLByAppendingPathExtension:@"mov"];
exporter.outputURL=fileURL;
exporter.outputFileType=AVFileTypeQuickTimeMovie;
[exporter exportAsynchronouslyWithCompletionHandler:^(void)
NSLog(@"Exporting done!");
NSLog(@"exporter's outputURL is %@", exporter.outputURL);
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
[self.view addSubview:self.moviePlayer.view];
self.moviePlayer.fullscreen = YES;
[self.moviePlayer play];
];
但是,在运行导出器后,电影无法在 self.moviePlayer
中播放。它只是“加载...”。请注意,我使用原始 videoURL 参数测试了moviePlayer
,并且效果很好。关于我做错了什么有什么想法吗?
谢谢
【问题讨论】:
【参考方案1】:需要:
dispatch_async(dispatch_get_main_queue(), ^
//play movie here
);
在完成处理程序中。
【讨论】:
以上是关于使用 AVAsset/AVCaptureSession 裁剪视频的主要内容,如果未能解决你的问题,请参考以下文章
在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?
Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)