在iOS中压缩视频

时间:2016-03-19 01:49:52

标签: ios avfoundation

我查看了this questionthis question,但都未能提供帮助。

我尝试了以下内容:

- (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]);
    }];
}

我知道self.movieUrl不是nil。但是当我打印与视频相关联的NSData的大小(以字节为单位)时,它们之前和之后都是相同的,都是30,000,000字节。

但根据this question,上述代码应该有效。

我到底做错了什么?

2 个答案:

答案 0 :(得分:16)

在Swift 3.0中

从相机胶卷中选择视频

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
     if info[UIImagePickerControllerMediaType] as? String == (kUTTypeMovie as? String) {
        // here your video capture code
        let videoURL = info[UIImagePickerControllerMediaURL] as! NSURL!
        let data = NSData(contentsOf: videoURL! as URL)!
        print("File size before compression: \(Double(data.length / 1048576)) mb")
        let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".m4v")
        compressVideo(inputURL: videoURL as! URL, outputURL: compressedURL) { (exportSession) in
                guard let session = exportSession else {
                    return
                }

                switch session.status {
                case .unknown:
                    break
                case .waiting:
                    break
                case .exporting:
                    break
                case .completed:
                    guard let compressedData = NSData(contentsOf: compressedURL) else {
                        return
                    }
                   print("File size after compression: \(Double(compressedData.length / 1048576)) mb")
                case .failed:
                    break
                case .cancelled:
                    break
                }
            }
       }
       self.dismiss(animated: true, completion: nil)
 }

压缩类型:

AVAssetExportPresetLowQuality
AVAssetExportPresetMediumQuality
AVAssetExportPresetHighestQuality
AVAssetExportPreset640x480 
AVAssetExportPreset960x540

压缩视频方法

 func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
        let urlAsset = AVURLAsset(url: inputURL, options: nil)
        guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetLowQuality) else {
            handler(nil)

            return
        }

        exportSession.outputURL = outputURL
        exportSession.outputFileType = AVFileTypeQuickTimeMovie
        exportSession.shouldOptimizeForNetworkUse = true
        exportSession.exportAsynchronously { () -> Void in
            handler(exportSession)
        }
    }

输出

File size before compression: 25.0 mb
File size after compression: 7.0 mb

答案 1 :(得分:6)

我已经弄明白了,感谢这个问题(Swift版本):IOS Video Compression Swift iOS 8 corrupt video file

我有目标C版。这是方法:

 - (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);
  }];
}

并调用方法:

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]);
    }
}];

这会将我的视频文件大小从32 MB减少到1.5 MB。