I've looked at this question and this question, neither have been able to help.
I have tried the following:
- (void)compress:(NSURL *)videoPath completionBlock:(void(^)(id data, BOOL result))block{
self.outputFilePath = [[NSString alloc] initWithFormat:@"%@%@", NSTemporaryDirectory(), @"output.mov"];
NSURL *outputURL = [NSURL fileURLWithPath:self.outputFilePath];
[self compressVideoWithURL:self.movieURL outputURL:outputURL handler:^(AVAssetExportSession *exportSession) {
}];
}
- (void)compressVideoWithURL:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
handler:(void (^)(AVAssetExportSession*))handler {
AVURLAsset *asset = [AVURLAsset assetWithURL:self.movieURL];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetLowQuality];
exportSession.fileLengthLimit = 3000000;
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
NSData *newOutputData = [NSData dataWithContentsOfURL:outputURL];
NSLog(@"Size of New Video(bytes):%d",[newOutputData length]);
}];
}
I know that self.movieUrl
is not nil
. But when I printed the size (in bytes) of the NSData
associated with the video, they were the same before and after, both 30,000,000 bytes.
But according to this question, the above code should work.
What am I doing wrong exactly?
I have figured it out, thanks to this question (Swift version): IOS Video Compression Swift iOS 8 corrupt video file
I have the objective C version. Here is the method:
- (void)compressVideo:(NSURL*)inputURL
outputURL:(NSURL*)outputURL
handler:(void (^)(AVAssetExportSession*))completion {
AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:urlAsset presetName:AVAssetExportPresetMediumQuality];
exportSession.outputURL = outputURL;
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
exportSession.shouldOptimizeForNetworkUse = YES;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
completion(exportSession);
}];
}
And calling the method:
NSURL* uploadURL = [NSURL fileURLWithPath:
[NSTemporaryDirectory() stringByAppendingPathComponent:@"temporaryPreview.mov"]];
[self compressVideo:self.movieURL outputURL:uploadURL handler:^(AVAssetExportSession *completion) {
if (completion.status == AVAssetExportSessionStatusCompleted) {
NSData *newDataForUpload = [NSData dataWithContentsOfURL:uploadURL];
NSLog(@"Size of new Video after compression is (bytes):%d",[newDataForUpload length]);
}
}];
This reduced the file size of my videos from 32 MB to 1.5 MB.