• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 拼接两个视频

[复制链接]
菜鸟教程小白 发表于 2022-12-12 09:37:19 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我需要创建一个由两个拼接视频组成的视频,如下图:

Two videos playing simultaneously - iOS simulator

实际上,我正在使用两个 AVPlayer 实例同时播放两个视频,但我需要使用这两个视频创建最终视频:Final video = [1 | 2]

您对如何做到这一点有任何想法吗?这是我用来播放这两个视频的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURL *url = [[NSBundle mainBundle] URLForResource"video_1" withExtension"mp4"];

    self.mPlayer = [AVPlayer playerWithURL:url];
    self.mPlayer2 = [AVPlayer playerWithURL:url];

    [self.mPlayer addObserver:self forKeyPath"status" options:0 context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
    [self.mPlayer2 addObserver:self forKeyPath"status" options:0 context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];
}

- (void)observeValueForKeyPathNSString*)path ofObjectid)object changeNSDictionary*)change contextvoid*)context
{
    if ([object isKindOfClass:[AVPlayer class]]) {
        if ([path isEqualToString"status"]) {
            switch(item.status) {
                case AVPlayerItemStatusFailed:
                    NSLog(@"player item status failed");
                    break;
                case AVPlayerItemStatusReadyToPlay:
                    NSLog(@"player item status is ready to play");
                    [self.mPlaybackView2 setPlayer:self.mPlayer2];
                    [self.mPlaybackView setPlayer:self.mPlayer];
                    [self.mPlayer play];
                    [self.mPlayer2 play];
                    break;
                case AVPlayerItemStatusUnknown:
                    NSLog(@"player item status is unknown");
                    break;
            }
        }
    }
}

来源:https://abdulazeem.wordpress.com/2012/04/02/



Best Answer-推荐答案


我找到了解决方案。我来了:

- (void)stitchAudioNSURL *)file1 audio2NSURL *)file2 {
    AVAsset *video1Asset = [AVAsset assetWithURL:file1];
    AVAsset *video2Asset = [AVAsset assetWithURL:file2];

    AVMutableComposition* mixComposition = [AVMutableComposition composition];

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

    AVMutableCompositionTrack *secondTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

    [secondTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, video2Asset.duration)
                         ofTrack:[[video2Asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
                          atTime:kCMTimeZero error:nil];

    //See how we are creating AVMutableVideoCompositionInstruction object.This object will contain the array of our AVMutableVideoCompositionLayerInstruction objects.You set the duration of the layer.You should add the lenght equal to the lingth of the longer asset in terms of duration.
    AVMutableVideoCompositionInstruction * MainInstruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
    MainInstruction.timeRange = CMTimeRangeMake(kCMTimeZero, video1Asset.duration);

    //We will be creating 2 AVMutableVideoCompositionLayerInstruction objects.Each for our 2 AVMutableCompositionTrack.here we are creating AVMutableVideoCompositionLayerInstruction for out first track.see how we make use of Affinetransform to move and scale our First Track.so it is displayed at the bottom of the screen in smaller size.(First track in the one that remains on top).
    AVMutableVideoCompositionLayerInstruction *FirstlayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:firstTrack];
    CGAffineTransform Scale = CGAffineTransformMakeScale(0.68f,0.68f);
    CGAffineTransform Move = CGAffineTransformMakeTranslation(0,0);
    [FirstlayerInstruction setTransform:CGAffineTransformConcat(Scale,Move) atTime:kCMTimeZero];

    //Here we are creating AVMutableVideoCompositionLayerInstruction for out second track.see how we make use of Affinetransform to move and scale our second Track.
    AVMutableVideoCompositionLayerInstruction *SecondlayerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:secondTrack];
    CGAffineTransform SecondScale = CGAffineTransformMakeScale(0.68f,0.68f);
    CGAffineTransform SecondMove = CGAffineTransformMakeTranslation(318,0);
    [SecondlayerInstruction setTransform:CGAffineTransformConcat(SecondScale,SecondMove) atTime:kCMTimeZero];

    //Now we add our 2 created AVMutableVideoCompositionLayerInstruction objects to our AVMutableVideoCompositionInstruction in form of an array.
    MainInstruction.layerInstructions = [NSArray arrayWithObjects:FirstlayerInstruction,SecondlayerInstruction,nil];

    //Now we create AVMutableVideoComposition object.We can add mutiple AVMutableVideoCompositionInstruction to this object.We have only one AVMutableVideoCompositionInstruction object in our example.You can use multiple AVMutableVideoCompositionInstruction objects to add multiple layers of effects such as fade and transition but make sure that time ranges of the AVMutableVideoCompositionInstruction objects dont overlap.
    AVMutableVideoComposition *MainCompositionInst = [AVMutableVideoComposition videoComposition];
    MainCompositionInst.instructions = [NSArray arrayWithObject:MainInstruction];
    MainCompositionInst.frameDuration = CMTimeMake(1, 30);
    MainCompositionInst.renderSize = CGSizeMake(640, 480);

    //Finally just add the newly created AVMutableComposition with multiple tracks to an AVPlayerItem and play it using AVPlayer.
    AVPlayerItem * newPlayerItem = [AVPlayerItem playerItemWithAsset:mixComposition];
    newPlayerItem.videoComposition = MainCompositionInst;
    self.mPlayer = [AVPlayer playerWithPlayerItem:newPlayerItem];
    [self.mPlaybackView setPlayer:self.mPlayer];
    [self.mPlayer play];
   // [self.mPlayer addObserver:self forKeyPath"status" options:0 context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];

    // Create the export session with the composition and set the preset to the highest quality.
    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    // Set the desired output URL for the file created by the export process.
    exporter.outputURL = [self newUniqueAudioFileURL];
    exporter.videoComposition = MainCompositionInst;
    // Set the output file type to be a QuickTime movie.
    exporter.outputFileType = AVFileTypeQuickTimeMovie;
    exporter.shouldOptimizeForNetworkUse = YES;

    // Asynchronously export the composition to a video file and save this file to the camera roll once export completes.
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];

                self.mPlayer = [AVPlayer playerWithURL:exporter.outputURL];
                //self.mPlayer2 = [AVPlayer playerWithURL:url];

                //[self.mPlayer addObserver:self forKeyPath"status" options:0 context:AVPlayerDemoPlaybackViewControllerStatusObservationContext];

                if ([assetsLibrary videoAtPathIsCompatibleWithSavedPhotosAlbum:exporter.outputURL]) {
                    [assetsLibrary writeVideoAtPathToSavedPhotosAlbum:exporter.outputURL completionBlock:NULL];
                }
            }
        });
    }];
}

来源:https://abdulazeem.wordpress.com/2012/04/02/

关于ios - 拼接两个视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23428582/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap