Ios 如何在AVMutableComposition中使用多个曲目

Ios 如何在AVMutableComposition中使用多个曲目,ios,avfoundation,avassetexportsession,avmutablecomposition,avasset,Ios,Avfoundation,Avassetexportsession,Avmutablecomposition,Avasset,请参阅下面的代码。我正在尝试添加第二首曲目,以便在背景视频上叠加一个较小的视频。但是,我只能在最终导出的文件中显示背景视频。我做错了什么?我如何控制音轨的顺序,即构图的分层 AVMutableComposition* composition = [[AVMutableComposition alloc] init]; NSURL* backgroundURL = [NSURL fileURLWithPath:backgroundOutputPath];

请参阅下面的代码。我正在尝试添加第二首曲目,以便在背景视频上叠加一个较小的视频。但是,我只能在最终导出的文件中显示背景视频。我做错了什么?我如何控制音轨的顺序,即构图的分层

    AVMutableComposition* composition = [[AVMutableComposition alloc] init];

    NSURL* backgroundURL = [NSURL fileURLWithPath:backgroundOutputPath];        
    AVURLAsset* url0 = [AVURLAsset URLAssetWithURL:backgroundURL options:nil];        

    AVMutableCompositionTrack *backgroundVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

    AVAssetTrack* bgAssetTrack = [[url0 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
    [backgroundVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [url0 duration])  ofTrack:bgAssetTrack atTime:kCMTimeZero error:&error];

     NSURL* videoURL = [[NSBundle mainBundle] URLForResource: @"star" withExtension:@"mp4"];
     AVURLAsset* url = [AVURLAsset URLAssetWithURL:videoURL options:nil];

     AVMutableCompositionTrack *compositionVideoTrack = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];

     AVAssetTrack *clipVideoTrack = [[url tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
     [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [url duration])  ofTrack:clipVideoTrack atTime:kCMTimeZero error:&error];



    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetMediumQuality];


    NSString *exportPath = [documentsDirectoryPath stringByAppendingPathComponent:@"test_AV.mp4"];

    [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
    NSURL *exportURL = [NSURL fileURLWithPath:exportPath];

    exportSession.outputURL = exportURL;
    exportSession.outputFileType = AVFileTypeQuickTimeMovie;

    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        NSLog (@"Exporting. status is %d",
               exportSession.status);
        switch (exportSession.status) {
            case AVAssetExportSessionStatusFailed:
            case AVAssetExportSessionStatusCompleted: {
                NSLog(@"export done");
                break;
            }
        };
    }];

查看本教程。这可能对您有所帮助:


嘿!我和我的团队正在为同样的问题疯狂。你解决了吗?