jjzjj

ios - AVMutableCompositionTrack 始终在添加水印后将 Portrait Video 旋转为 Landscape

coder 2024-01-16 原文

从最近 2 天开始,我一直在为 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 的解决方案对我没有用。

我必须保持其横向。我什至尝试在 compositionVideoTracklayerInstruction 上设置转换,但它们都没有帮助我。

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

最佳答案

最后,我得到了解决方案,parentLayervideoLayer 的大小造成了问题。随着 render.renderSizelayerInstruction 转换需要更改。这是代码:

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") ;
    }
}];

关于ios - AVMutableCompositionTrack 始终在添加水印后将 Portrait Video 旋转为 Landscape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31405752/

有关ios - AVMutableCompositionTrack 始终在添加水印后将 Portrait Video 旋转为 Landscape的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  3. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  4. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  5. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  6. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  7. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

  8. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  9. ruby - 我如何添加二进制数据来遏制 POST - 2

    我正在尝试使用Curbgem执行以下POST以解析云curl-XPOST\-H"X-Parse-Application-Id:PARSE_APP_ID"\-H"X-Parse-REST-API-Key:PARSE_API_KEY"\-H"Content-Type:image/jpeg"\--data-binary'@myPicture.jpg'\https://api.parse.com/1/files/pic.jpg用这个:curl=Curl::Easy.new("https://api.parse.com/1/files/lion.jpg")curl.multipart_form_

  10. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

随机推荐