如何在AVMutableComposition中使用多个轨道

时间:2014-01-31 18:07:24

标签: ios avfoundation avassetexportsession avmutablecomposition avasset

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

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