Skip to content

Instantly share code, notes, and snippets.

@yangyi
Created October 21, 2014 08:34
Show Gist options
  • Save yangyi/8f92534a0cefba9a76e8 to your computer and use it in GitHub Desktop.
Save yangyi/8f92534a0cefba9a76e8 to your computer and use it in GitHub Desktop.
-(AVVideoComposition *)squareCropperVideoComposition:(AVAssetTrack *)clipVideoTrack {
AVMutableVideoComposition * videoComposition = [AVMutableVideoComposition videoComposition];
CGSize originVideoSize = clipVideoTrack.naturalSize;
CGFloat shortSideLength = MIN(originVideoSize.width, originVideoSize.height);
CGFloat longSideLength = MAX(originVideoSize.width, originVideoSize.height);
CGFloat renderSideLength = 640.0; // MIN(640.0, shortSideLength);
CGFloat scale = renderSideLength / shortSideLength;
videoComposition.renderSize = CGSizeMake(renderSideLength, renderSideLength);
videoComposition.frameDuration = CMTimeMake(1, 30);
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = clipVideoTrack.timeRange;
AVMutableVideoCompositionLayerInstruction* cropper = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack];
CGAffineTransform t = CGAffineTransformIdentity; //CGAffineTransformMakeRotation(M_PI_2);
if (_cameraPosition == AVCaptureDevicePositionFront) {
t = CGAffineTransformTranslate(t, renderSideLength, 0);
t = CGAffineTransformScale(t, -1, 1);
}
t = CGAffineTransformRotate(t, M_PI_2);
t = CGAffineTransformScale(t, scale, scale);
t = CGAffineTransformTranslate(t, -(longSideLength - shortSideLength) / 2, -shortSideLength);
[cropper setTransform:t atTime:kCMTimeZero];
instruction.layerInstructions = @[cropper];
videoComposition.instructions = @[instruction];
return videoComposition;
}
AVMutableComposition * mutableComposition = [AVMutableComposition composition];
AVMutableCompositionTrack * videoTrack = [mutableComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
AVMutableCompositionTrack * audioTrack = [mutableComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack * vt = [asset tracksWithMediaType:AVMediaTypeVideo][0];
AVAssetTrack * at = [asset tracksWithMediaType:AVMediaTypeAudio][0];
[videoTrack insertTimeRange:vt.timeRange ofTrack:vt atTime:kCMTimeZero error:nil];
[audioTrack insertTimeRange:at.timeRange ofTrack:at atTime:kCMTimeZero error:nil];
AVAssetExportSession *_exporter = [[AVAssetExportSession alloc] initWithAsset:mutableComposition presetName:AVAssetExportPresetHighestQuality];
_exporter.videoComposition = [self squareCropperVideoComposition:videoTrack];
_exporter.outputFileType = AVFileTypeMPEG4;
_exporter.outputURL = ... some file url
[_exporter exportAsynchronouslyWithCompletionHandler:^{
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment