How to write a movie with video AND audio using AVAssetWriter?

后端 未结 2 781
囚心锁ツ
囚心锁ツ 2021-01-31 19:16

I want to export a movie with AVAssetWriter and can\'t figure out how to include video and audio tracks in sync. Exporting only video works fine, but when I add aud

2条回答
  •  不思量自难忘°
    2021-01-31 19:57

    -(void)mergeAudioVideo
    {
    
        NSString *videoOutputPath=[_documentsDirectory stringByAppendingPathComponent:@"dummy_video.mp4"];
        NSString *outputFilePath = [_documentsDirectory stringByAppendingPathComponent:@"final_video.mp4"];
        if ([[NSFileManager defaultManager]fileExistsAtPath:outputFilePath])
            [[NSFileManager defaultManager]removeItemAtPath:outputFilePath error:nil];
    
    
        NSURL    *outputFileUrl = [NSURL fileURLWithPath:outputFilePath];
        NSString *filePath = [_documentsDirectory stringByAppendingPathComponent:@"newFile.m4a"];
        AVMutableComposition* mixComposition = [AVMutableComposition composition];
    
        NSURL    *audio_inputFileUrl = [NSURL fileURLWithPath:filePath];
        NSURL    *video_inputFileUrl = [NSURL fileURLWithPath:videoOutputPath];
    
        CMTime nextClipStartTime = kCMTimeZero;
    
        AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:video_inputFileUrl options:nil];
        CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
    
        AVMutableCompositionTrack *a_compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        [a_compositionVideoTrack insertTimeRange:video_timeRange ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:nextClipStartTime error:nil];
    
        AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audio_inputFileUrl options:nil];
        CMTimeRange audio_timeRange = CMTimeRangeMake(kCMTimeZero, audioAsset.duration);
        AVMutableCompositionTrack *b_compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [b_compositionAudioTrack insertTimeRange:audio_timeRange ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:nextClipStartTime error:nil];
    
        AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
        _assetExport.outputFileType = @"com.apple.quicktime-movie";
        _assetExport.outputURL = outputFileUrl;
    
        [_assetExport exportAsynchronouslyWithCompletionHandler:
         ^(void ) {
             if (_assetExport.status == AVAssetExportSessionStatusCompleted) {
    
              //Write Code Here to Continue
             }
             else {
                //Write Fail Code here     
             }
         }
         ];
    
    
    
    }
    

    You can use this code to merge audio and video.

提交回复
热议问题