使用 AVAsset/AVCaptureSession 裁剪视频

Cropping a video with AVAsset/AVCaptureSession

我正在尝试将视频裁剪成正方形。我已经有一个生成矩形分辨率 .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 并且播放正常。关于我做错了什么的想法?

谢谢

需要:

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

在完成处理程序中。