merging videos together (AVFoundation)

前端 未结 4 2175
心在旅途
心在旅途 2021-02-06 18:17

In my app, I\'m recording small videos and adding them into an NSMutableArray as AVAsset so that i keep record of what has been captured. when the user

4条回答
  •  故里飘歌
    2021-02-06 18:57

    This will work fine

          AVMutableComposition *mainComposition = [[AVMutableComposition alloc] init];
          AVMutableCompositionTrack *compositionVideoTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    
    
          AVMutableCompositionTrack *soundtrackTrack = [mainComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
          CMTime insertTime = kCMTimeZero;
    
          for (AVAsset *videoAsset in assets) {
    
              [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:insertTime error:nil];
    
              [soundtrackTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:insertTime error:nil];
    
              // Updating the insertTime for the next insert
              insertTime = CMTimeAdd(insertTime, videoAsset.duration);
          }
    
          NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
          NSString *documentsDirectory = [paths objectAtIndex:0];
    
          // Creating a full path and URL to the exported video
          NSString *outputVideoPath =  [documentsDirectory stringByAppendingPathComponent:
                                  [NSString stringWithFormat:@"mergeVideo-%d.mov",arc4random() % 1000]];
    
          // NSString *documentsDirectory = [paths objectAtIndex:0];
          NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:
                             current_name];
          NSURL *outptVideoUrl = [NSURL fileURLWithPath:myPathDocs];
          AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mainComposition presetName:AVAssetExportPreset640x480];
    
          // Setting attributes of the exporter
          exporter.outputURL=outptVideoUrl;
          exporter.outputFileType =AVFileTypeMPEG4;   //AVFileTypeQuickTimeMovie;
          exporter.shouldOptimizeForNetworkUse = YES;
          [exporter exportAsynchronouslyWithCompletionHandler:^{
              dispatch_async(dispatch_get_main_queue(), ^{
                  //completion(exporter);
                  [self exportDidFinish:exporter];
                  // [self exportDidFinish:exporter:assets];
              });
          }];
    

    this will work fine..

提交回复
热议问题