添加水印后,AVMutableCompositionTrack始终将纵向视频旋转为横向

时间:2015-07-14 11:49:17

标签: ios iphone ios8 avfoundation

从过去的两天开始,我正在用AVMutableCompositionTrack轻描淡写,在我的情况下,它需要一个人像视频,但在添加水印后,它会变成风景。

这是我的代码:

AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:[[NSBundle mainBundle] URLForResource:@"Sample" withExtension:@".mp4"] options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];

AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo  preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *clipVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
                               ofTrack:clipVideoTrack
                                atTime:kCMTimeZero error:nil];

[compositionVideoTrack setPreferredTransform:[videoAsset preferredTransform]];

//WaterMark
UIImage *waterMark = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Sample.jpg"]];
CALayer *waterMarkLayer = [CALayer layer];
[waterMarkLayer setContents:(id)[waterMark CGImage]];
[waterMarkLayer setFrame:CGRectMake(30, 30, 100, 40)] ;
[waterMarkLayer setOpacity:0.8] ;

CGSize videoSize = [[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] naturalSize];
CALayer *parentLayer = [CALayer layer];
CALayer *videoLayer = [CALayer layer];
[parentLayer setFrame:CGRectMake(0, 0, videoSize.width, videoSize.height)];
[videoLayer setFrame:CGRectMake(0, 0, videoSize.width, videoSize.height)];
[parentLayer addSublayer:videoLayer];
[parentLayer addSublayer:waterMarkLayer];

//Instruction
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
[instruction setTimeRange:CMTimeRangeMake(kCMTimeZero, [mixComposition duration])];
AVAssetTrack *videoTrack = [[mixComposition tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];

AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
[instruction setLayerInstructions:[NSArray arrayWithObject:layerInstruction]];

AVMutableVideoComposition *videoComp = [AVMutableVideoComposition videoComposition] ;
[videoComp setRenderSize:videoSize];
[videoComp setFrameDuration:CMTimeMake(1, 30)];
[videoComp setAnimationTool:[AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer]];
[videoComp setInstructions:[NSArray arrayWithObject:instruction]];

//Exporting File
NSString *fullMoviePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"WaterMarkedMovie" stringByAppendingPathExtension:@"mp4"]];
NSURL *finalVideoFileURL = [NSURL fileURLWithPath:fullMoviePath];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
[exportSession setOutputFileType:AVFileTypeMPEG4];
[exportSession setOutputURL:finalVideoFileURL];
[exportSession setVideoComposition:videoComp];

[exportSession exportAsynchronouslyWithCompletionHandler:^{

    switch ([exportSession status])
    {
        case AVAssetExportSessionStatusFailed:
        {
            NSLog(@"Export Failed: %@ %@", [[exportSession error] localizedDescription], [[exportSession error] debugDescription]);

            [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

            break ;
        }
        case AVAssetExportSessionStatusCancelled:
        {
            NSLog(@"Export Cancel: %@ %@", [[exportSession error] localizedDescription], [[exportSession error] debugDescription]);

            [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

            break ;
        }
        case AVAssetExportSessionStatusCompleted:
        {
            NSLog(@"Export Complete!");

            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

                if (status == PHAuthorizationStatusAuthorized)
                {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[exportSession outputURL]];
                    } completionHandler:^(BOOL success, NSError *error) {

                        [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

                        if (success)
                        {
                            NSLog(@"Success");
                        }
                    }];
                }
                else
                {
                    NSLog(@"Not Authorised");

                    [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];
                }
            }];

            break ;
        }
        default : NSLog(@"Default") ;
    }
}];

我已尝试过所有重复查找的问题,但Stackoverflow的解决方案对我没有任何帮助。

我必须保持其横向方向。我甚至尝试在compositionVideoTrack&上设置转换。 layerInstruction但他们都没有帮助我。

任何建议都会有所帮助。 :)

1 个答案:

答案 0 :(得分:3)

最后,我得到了parentLayer&的大小的解决方案。 videoLayer正在制造问题。与render.renderSize&需要更改layerInstruction转换。这是代码:

AVURLAsset *videoAsset = [[AVURLAsset alloc]initWithURL:[[NSBundle mainBundle] URLForResource:@"Sample" withExtension:@".mp4"] options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];

AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo  preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *clipVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
                               ofTrack:clipVideoTrack
                                atTime:kCMTimeZero error:nil];

//WaterMark
UIImage *waterMark = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Sample.jpg"]];
CALayer *waterMarkLayer = [CALayer layer];
[waterMarkLayer setContents:(id)[waterMark CGImage]];
[waterMarkLayer setFrame:CGRectMake(30, 30, 100, 40)] ;
[waterMarkLayer setOpacity:0.8] ;

AVAssetTrack *assetVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] ;
CGSize videoSize = [assetVideoTrack naturalSize];

CALayer *parentLayer = [CALayer layer];
CALayer *videoLayer = [CALayer layer];
[parentLayer setFrame:CGRectMake(0, 0, videoSize.height, videoSize.width)];
[videoLayer setFrame:CGRectMake(0, 0, videoSize.height, videoSize.width)];
[parentLayer addSublayer:videoLayer];
[parentLayer addSublayer:waterMarkLayer];

//Instruction
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
[instruction setTimeRange:CMTimeRangeMake(kCMTimeZero, [mixComposition duration])];
AVAssetTrack *videoTrack = [[mixComposition tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];

AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];

CGAffineTransform t1 = CGAffineTransformMakeTranslation(videoSize.height, 0);
CGAffineTransform t2 = CGAffineTransformRotate(t1, degreesToRadians(90.0));
[layerInstruction setTransform:t2 atTime:kCMTimeZero];
[instruction setLayerInstructions:[NSArray arrayWithObject:layerInstruction]];

AVMutableVideoComposition *videoComp = [AVMutableVideoComposition videoComposition] ;
[videoComp setRenderSize:CGSizeMake(videoSize.height, videoSize.width)];
[videoComp setFrameDuration:CMTimeMake(1, 30)];
[videoComp setAnimationTool:[AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer]];
[videoComp setInstructions:[NSArray arrayWithObject:instruction]];

//Exporting File
NSString *fullMoviePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[@"WaterMarkedMovie" stringByAppendingPathExtension:@"mp4"]];
NSURL *finalVideoFileURL = [NSURL fileURLWithPath:fullMoviePath];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
[exportSession setOutputFileType:AVFileTypeMPEG4];
[exportSession setOutputURL:finalVideoFileURL];
[exportSession setVideoComposition:videoComp];

[exportSession exportAsynchronouslyWithCompletionHandler:^{

    switch ([exportSession status])
    {
        case AVAssetExportSessionStatusFailed:
        {
            NSLog(@"Export Failed: %@ %@", [[exportSession error] localizedDescription], [[exportSession error] debugDescription]);

            [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

            break ;
        }
        case AVAssetExportSessionStatusCancelled:
        {
            NSLog(@"Export Cancel: %@ %@", [[exportSession error] localizedDescription], [[exportSession error] debugDescription]);

            [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

            break ;
        }
        case AVAssetExportSessionStatusCompleted:
        {
            NSLog(@"Export Complete!");

            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

                if (status == PHAuthorizationStatusAuthorized)
                {
                    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                        [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[exportSession outputURL]];
                    } completionHandler:^(BOOL success, NSError *error) {

                        [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];

                        if (success)
                        {
                            NSLog(@"Success");
                        }
                    }];
                }
                else
                {
                    NSLog(@"Not Authorised");

                    [[NSFileManager defaultManager] removeItemAtURL:[exportSession outputURL] error:nil];
                }
            }];

            break ;
        }
        default : NSLog(@"Default") ;
    }
}];