AVMutableComposition удалить звуковую дорожку видео

Я пытался смешать аудио (записанное) с видео (.mp4) с помощью AVMutableComposition, что означает, что мне нужно, чтобы 2 файла воспроизводились параллельно после микширования, вот код, который я использовал: audiosURL — это URL-адрес видеофайла.

NSURL *audiosURL =[[NSURL alloc] initFileURLWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"dam3.mp4"] ofType:nil]];

        NSLog(@"SOMEDATA    IS THERE ");
        AVURLAsset* audioAsset  = [[AVURLAsset alloc]initWithURL:temporaryRecFile options:nil];
        AVURLAsset* audio2Asset = [[AVURLAsset alloc]initWithURL:audiosURL options:nil];

        AVMutableComposition* mixComposition = [AVMutableComposition composition];

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

        NSLog(@"audio =%@",audioAsset);
        AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];


        AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetPassthrough];

        NSString* videoName = @"export.mov";

        NSString *exportPath = [NSTemporaryDirectory() stringByAppendingPathComponent:videoName];
        NSURL    *exportUrl = [NSURL fileURLWithPath:exportPath];

        if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath])
        {
            [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
        }

    _assetExport.outputFileType = AVFileTypeQuickTimeMovie;
    //@"com.apple.quicktime-movie";
        NSLog(@"file type %@",_assetExport.outputFileType);
        _assetExport.outputURL = exportUrl;
        _assetExport.shouldOptimizeForNetworkUse = YES;



        [_assetExport exportAsynchronouslyWithCompletionHandler:
         ^(void )
         {
             switch (_assetExport.status)
             {
                 case AVAssetExportSessionStatusCompleted:
                     //   export complete

                     NSLog(@"Export Complete");
                    // From Here I want play movie using MPMoviePlayerController.<<<---------
                     NSString  *fileNamePath = @"sound_record.mov";
                     NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                     NSString  *documentsDirectory = [paths  objectAtIndex:0];
                     NSString  *oldappSettingsPath = [documentsDirectory stringByAppendingPathComponent:fileNamePath];


                     if ([[NSFileManager defaultManager] fileExistsAtPath:oldappSettingsPath]) {

                         NSFileManager *fileManager = [NSFileManager defaultManager];
                         [fileManager removeItemAtPath: oldappSettingsPath error:NULL];

                     }
                     NSURL *documentDirectoryURL = [NSURL fileURLWithPath:oldappSettingsPath];
                     [[NSFileManager defaultManager] copyItemAtURL:exportUrl toURL:documentDirectoryURL error:nil];
                     [audioAsset release];
                     [audio2Asset release];
                     [_assetExport release];
                     [self performSelectorOnMainThread:@selector(playVideo:) withObject:documentDirectoryURL waitUntilDone:NO];

                     break;
                 case AVAssetExportSessionStatusFailed:
                     NSLog(@"Export Failed");
                     NSLog(@"ExportSessionError: %@", [_assetExport.error localizedDescription]);

                     //                export error (see exportSession.error)
                     break;
                 case AVAssetExportSessionStatusCancelled:
                     NSLog(@"Export Failed");
                     NSLog(@"ExportSessionError: %@", [_assetExport.error localizedDescription]);

                     //                export cancelled  
                     break;

             }
         }
         ];

В результате экспортированное видео воспроизводит записанный звук с видео успешно, но звуковая дорожка видео была удалена, поэтому экспортированный .mov воспроизводит записанный аудиофайл с изображением видео только без его звука, почему это происходит?


person Hash.Techniq    schedule 11.03.2013    source источник


Ответы (1)


Вам нужно будет добавить звук из видео в виде отдельной дорожки. Таким образом, у вас будет одна видеодорожка и две звуковые дорожки. В вашем коде у вас нет звука из добавляемого видео.

person BooTooMany    schedule 28.03.2013