使用AVAsset / AVCaptureSession裁剪视频

时间:2015-01-14 00:14:17

标签: ios ios8 avcapturesession avassetexportsession

我正在尝试将视频剪裁成正方形。我已经有一个AVCaptureSession设置,可以生成矩形分辨率.mov文件。所以我只想用我发现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 个答案:

答案 0 :(得分:1)

需要:

dispatch_async(dispatch_get_main_queue(), ^{
  //play movie here
});

在完成处理程序中。