ios 音视频剪切、添加水印、视频旋转

核心代码

1,创建需要处理的视频素材,

#pragma mark - 视频编辑
-(void)videoEdit{
    //1,将素材拖入到素材库
    AVAsset *asset = [AVAsset assetWithURL:self.videoUrl];
    //素材的视频轨
    AVAssetTrack *videoAssetTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    //素材的音频轨
    AVAssetTrack *audioAssetTrack = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
    
    // Trim to half duration
//    double halfDuration = CMTimeGetSeconds([asset duration]) - 5;
    CMTime trimmedDuration = CMTimeSubtract(_videoView.newEndTime, _videoView.newStartTime);
    CMTimeShow(trimmedDuration);

    //2,将素材的视频插入视频轨,音频插入音频轨
    //这是工程文件
    self.composition  = [AVMutableComposition composition];
    //视频轨道
    AVMutableCompositionTrack *videoCompositionTrack = [self.composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    //在视频轨道插入一个时间段的视频
    [videoCompositionTrack insertTimeRange:CMTimeRangeMake(_videoView.newStartTime, trimmedDuration) ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];
    //音频轨道
    AVMutableCompositionTrack *audioCompositionTrack = [self.composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    //插入音频数据,否则没声音
    [audioCompositionTrack insertTimeRange:CMTimeRangeMake(_videoView.newStartTime,trimmedDuration) ofTrack:audioAssetTrack atTime:kCMTimeZero error:nil];
    //可以添加其他音视频
//    [videoCompositionTrack insertTimeRange:CMTimeRangeMake(_newStartTime, trimmedDuration) ofTrack:videoAssetTrack atTime:kCMTimeZero error:nil];
    
//    //3,裁剪视频
    //AVMutableVideoComposition:管理所有视频轨道,可以决定最终视频的尺寸,裁剪需要在这里进行
    self.videoComposition = [AVMutableVideoComposition videoComposition];
    self.videoComposition.frameDuration = CMTimeMake(1, 30);
    self.videoComposition.renderSize = videoAssetTrack.naturalSize;
    
//    AVMutableVideoCompositionInstruction 视频轨道中的一个视频,可以缩放、旋转等
    AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, trimmedDuration);
    // 3.2 AVMutableVideoCompositionLayerInstruction 一个视频轨道,包含了这个轨道上的所有视频素材
    AVAssetTrack *videoTrack = [self.composition tracksWithMediaType:AVMediaTypeVideo][0];
    AVMutableVideoCompositionLayerInstruction *layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
    //视频旋转处理
    if (self.isRotate) {
        CGAffineTransform t1 = CGAffineTransformMakeTranslation(videoCompositionTrack.naturalSize.height, 0.0);
        // Rotate transformation
        CGAffineTransform  t2 = CGAffineTransformRotate(t1, degreesToRadians(90.0));
        [layerInstruction setTransform:t2 atTime:kCMTimeZero];
        self.videoComposition.renderSize = CGSizeMake(videoAssetTrack.naturalSize.height,  videoAssetTrack.naturalSize.width);
    }
    
    // 3.3 - Add instructions
    instruction.layerInstructions = [NSArray arrayWithObjects:layerInstruction,nil];
    self.videoComposition.instructions = [NSArray arrayWithObject:instruction];
    
    //添加水印 重新刷新player的时候会重置 所以在导出水印的时候添加水印

}

2,视频旋转,添加水印
视频处理后需要刷新 player,刷新前必须调用 self.videoComposition.animationTool = NULL;
会把水印清空,所以添加水印要在导出前添加,显示在palyerLayer上的水印为"假水印"

    if (self.isAddWaterMark) {
        CGSize videoSize = self.videoComposition.renderSize;
        self.watermarkLayer = [self watermarkLayerForSize:videoSize];
        CALayer *exportWatermarkLayer = [self copyWatermarkLayer:self.watermarkLayer];
        CALayer *parentLayer = [CALayer layer];
        CALayer *videoLayer = [CALayer layer];
        parentLayer.frame = CGRectMake(0, 0, self.videoComposition.renderSize.width, self.videoComposition.renderSize.height);
        videoLayer.frame = CGRectMake(0, 0, self.videoComposition.renderSize.width, self.videoComposition.renderSize.height);
        [parentLayer addSublayer:videoLayer];
        exportWatermarkLayer.position = CGPointMake(self.videoComposition.renderSize.width/2, self.videoComposition.renderSize.height/4);
        [parentLayer addSublayer:exportWatermarkLayer];
        
        CABasicAnimation *anima = [CABasicAnimation animationWithKeyPath:@"opacity"];
        anima.fromValue = [NSNumber numberWithFloat:1.0f];
        anima.toValue = [NSNumber numberWithFloat:0.0f];
        anima.repeatCount = 0;
        anima.duration = 5.0f;  //5s之后消失
        [anima setRemovedOnCompletion:NO];
        [anima setFillMode:kCAFillModeForwards];
        anima.beginTime = AVCoreAnimationBeginTimeAtZero;
        [exportWatermarkLayer addAnimation:anima forKey:@"opacityAniamtion"];
        
        self.videoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
    }

3,导出视频

    //保存至沙盒路径
    [self creatSandBoxFilePathIfNoExist];
    //保存至沙盒路径
    NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *videoPath = [NSString stringWithFormat:@"%@/Video", pathDocuments];
    NSString *urlPath = [videoPath stringByAppendingPathComponent:@"cyan.mp4"];
    //先移除
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager removeItemAtPath:urlPath error:nil];
    
    //    AVAssetExportPresetPassthrough AVAssetExportPresetHighestQuality
   self.exportSession = [[AVAssetExportSession alloc] initWithAsset:self.composition presetName:AVAssetExportPresetHighestQuality];
    
    self.exportSession.videoComposition = self.videoComposition;
    self.exportSession.outputURL = [NSURL fileURLWithPath:urlPath];
    self.exportSession.outputFileType = AVFileTypeMPEG4;
    //    exporter.shouldOptimizeForNetworkUse = YES;
    
    [self.exportSession exportAsynchronouslyWithCompletionHandler:^{
        int exportStatus = self.exportSession.status;
        NSLog(@"exportStatus : %d",exportStatus);
        switch (exportStatus)
        {
            case AVAssetExportSessionStatusFailed:
            {
                // log error to text view
                NSError *exportError = self.exportSession.error;
                NSLog (@"AVAssetExportSessionStatusFailed: %@", exportError);
                break;
            }
            case AVAssetExportSessionStatusCompleted:
            {
                //保存到相册
                [self writeVideoToPhotoLibrary:[NSURL fileURLWithPath:urlPath]];
                
                NSLog(@"视频转码成功");
                
            }
        }
    }];

读取解析视频帧图片,用来可视化裁剪视频,

#pragma mark - 读取解析视频帧图片
-(void)analysisVideoFrames{
    AVURLAsset *videoAsset = [[AVURLAsset alloc]initWithURL:self.videoUrl options:nil];
    //获取视频总长度 = 总帧数 / 每秒的帧数
    long videoSumTime = videoAsset.duration.value / videoAsset.duration.timescale;
    //创建AVAssetImageGenerator对象
    AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc]initWithAsset:videoAsset];
    generator.maximumSize = self.bottomView.frame.size;
    generator.appliesPreferredTrackTransform = YES;
    generator.requestedTimeToleranceBefore = kCMTimeZero;
    generator.requestedTimeToleranceAfter = kCMTimeZero;
    
    //添加需要帧数的时间集合
    self.framesArray = [NSMutableArray array];
    for (NSInteger index = 0; index < videoSumTime; index ++) {
        CMTime time = CMTimeMake(index * videoAsset.duration.timescale, videoAsset.duration.timescale);
        NSValue *value = [NSValue valueWithCMTime:time];
        [self.framesArray addObject:value];
    }
    
    
    __block long count = 0 ;
    __weak typeof(self)weakSelf = self;
    __block UIImage *showImage = [[UIImage alloc] init];
    __block CGFloat showImageViewWitd = (self.bottomView.frame.size.width - self.leftView.frame.size.width * 2)/videoSumTime;
    [generator generateCGImagesAsynchronouslyForTimes:self.framesArray completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (result == AVAssetImageGeneratorSucceeded) {
            showImage = [UIImage imageWithCGImage:image];
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImageView *thumImgView = [[UIImageView alloc]initWithFrame:CGRectMake( 20 +  count * showImageViewWitd , 0, showImageViewWitd, 40)];
                thumImgView.image = showImage;
                [weakSelf.showImageViewBgView addSubview:thumImgView];
                count++;
            }) ;
        }
        if (result == AVAssetImageGeneratorFailed) {
            NSLog(@"Failed with error: %@", [error localizedDescription]);
        }
        
        if (result == AVAssetImageGeneratorCancelled) {
            NSLog(@"AVAssetImageGeneratorCancelled");
        }
    }];
    
}

demo https://github.com/MuRanJiangXia/DouyinPlay

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,172评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,346评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,788评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,299评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,409评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,467评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,476评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,262评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,699评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,994评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,167评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,499评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,149评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,387评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,028评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,055评论 2 352

推荐阅读更多精彩内容