Monday, 1 June 2015

How to Compress Video File Through coding in iOS

  1. - (void)compressMyVideo:(NSURL *)videoPath completionBlock:(void(^)(id data, BOOL result))block{
  2. NSLog(@"compressing ====%@", videoPath);
  3. completionBlock = block;
  4. NSURL *videoURL = videoPath;//[NSURL fileURLWithPath:videoPath];
  5. NSLog(@"video url is== %@", videoURL);
  6. NSString *outputPath = [self outputFilePath];
  7. NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
  8. [self convertVideoToLowQuailtyWithInputURL:videoURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession)
  9. {
  10. if (exportSession.status == AVAssetExportSessionStatusCompleted)
  11. {
  12. printf("completed\n");
  13. completionBlock(outputURL, YES);
  14. }
  15. else
  16. {
  17. printf("error\n");
  18. completionBlock(nil, NO);
  19. }
  20. }];
  21. }
  22. // Getting the path of outPut file
  23. - (NSString *)outputFilePath{
  24. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  25. NSString *documentsDirectory = [paths objectAtIndex:0];
  26. NSString *path = [documentsDirectory stringByAppendingPathComponent:@"compressed.MOV"]; NSFileManager *fileManager = [NSFileManager defaultManager];
  27. // return path;
  28. if ([fileManager fileExistsAtPath: path])
  29. {
  30. [fileManager removeItemAtPath:path error:nil];
  31. }
  32. path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @"compressed.MOV"] ];
  33. NSLog(@"path is== %@", path);
  34. return path;
  35. }
  36. // Actual compression is here.
  37. - (void)convertVideoToLowQuailtyWithInputURL:(NSURL*)inputURL
  38. outputURL:(NSURL*)outputURL
  39. handler:(void (^)(AVAssetExportSession*))handler
  40. {
  41. // [self startCompressingTheVideo:outputURL];
  42. //
  43. //
  44. // return;
  45. [[NSFileManager defaultManager] removeItemAtURL:outputURL error:nil];
  46. // AVAssetWriter
  47. AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
  48. AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
  49. // exportSession.fileLengthLimit = 30*1024;
  50. exportSession.outputURL = outputURL;
  51. exportSession.outputFileType = AVFileTypeQuickTimeMovie;
  52. [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
  53. {
  54. handler(exportSession);
  55. // [exportSession release];
  56. }];
  57. }

For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment