Objective-c如何为Instagram应用程序等现有视频添加过滤器?

时间:2017-06-19 07:34:37

标签: ios objective-c video gpuimage cifilter

我正在尝试在录制后为视频添加过滤器,就像Instagram一样。在搜索了我找到GPUImage的方法之后,但由于在此代码中视频在显示之前被写入目录(导致延迟),因此无法解决问题:

//Setting path for temporary storing the video in document directory
NSURL *movieURL = [self dataFilePath: @"tempVideo.mp4"]; // url where we want to save our new edited video

有没有办法在保存之前预览已过滤的视频,以免花费时间?如果是这样,它是如何完成的?

另外,我在苹果文档中找到了有关CIFilter的信息,但仍未找到说明如何向视频添加过滤器的方法。

另外,有一些代码但是用swift编写。

提前致谢。

1 个答案:

答案 0 :(得分:1)

我无法找到一种方法来阻止使用GPUImage的延迟。所以我尝试使用SCRecorder

我所做的是:

[_player setItemByUrl:videoURL];

而不是:

[_player setItemByAsset:_recordSession.assetRepresentingSegments];
通过这种方式,我可以像Instagram一样播放现有视频并添加过滤器。

要使用所选过滤器导出视频,我使用了以下代码:

 - (void)saveToCameraRoll {

  NSString *fileName = videoURL.lastPathComponent;
  NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *docsDir = [dirPaths objectAtIndex:0];
  NSString *videoPath = [NSString stringWithFormat:@"%@/%@",docsDir,fileName];
  NSURL *urlPath = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@", videoPath]];

  NSURL *assetUrl = urlPath;
  AVAsset *asset = [AVAsset assetWithURL:assetUrl];
  SCFilter *exportFilter = [self.filterSwitcherView.selectedFilter copy];

  SCAssetExportSession *exportSession = [[SCAssetExportSession alloc] initWithAsset:asset];
  NSURL *urlFile = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@.mov",docsDir,fileName]];
  exportSession.outputUrl = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@",urlFile]];

  filterURL = exportSession.outputUrl;

  exportSession.videoConfiguration.filter = exportFilter;
  exportSession.videoConfiguration.preset = SCPresetHighestQuality;
  exportSession.audioConfiguration.preset = SCPresetHighestQuality;
  exportSession.videoConfiguration.maxFrameRate = 35;
  exportSession.outputFileType = AVFileTypeMPEG4;
  exportSession.delegate = self;
  exportSession.contextType = SCContextTypeAuto;
  self.exportSession = exportSession;

  [exportSession exportAsynchronouslyWithCompletionHandler:^{
      if (exportSession.error == nil) {
          [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
          [exportSession.outputUrl saveToCameraRollWithCompletion:^(NSString * _Nullable path, NSError * _Nullable error) {
              [[UIApplication sharedApplication] endIgnoringInteractionEvents];

              if (error == nil) {
                //Success
              }
          }];

      } else {
          NSLog(@"Error: %@", exportSession.error);
      }
  }];
}