2

Please see the code below. I'm trying to add a 2nd track so that I have a smaller video overlaid on top of a background video. However I can only get the background video to display in the final exported file. What am I doing wrong? And how do I control the order of tracks, i.e. the layering of the composition?

    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;
            }
        };
    }];
soleil
  • 12,133
  • 33
  • 112
  • 183