我正在尝试使用UI
ImagePickerController(不是现有的视频,而是一个在线)上的用户相机拍摄的视频,以上传到我的服务器,花费少量的时间来做到这一点,所以更小的尺寸是理想的,而不是30- 45Mb的新品质相机.
以下是针对iOS 8的Swift进行压缩的代码,它可以令人惊奇地压缩,从35 mb下降到2.1 mb.
func convertVideo(inputUrl: NSURL,outputURL: NSURL) { //setup video writer var videoAsset = AVURLAsset(URL: inputUrl,options: nil) as AVAsset var videoTrack = videoAsset.tracksWithMediaType(AVMediaTypeVideo)[0] as AVAssetTrack var videoSize = videoTrack.naturalSize var videoWriterCompressionSettings = Dictionary(dictionaryLiteral:(AVVideoAverageBitRateKey,NSNumber(integer:960000))) var videoWriterSettings = Dictionary(dictionaryLiteral:(AVVideoCodecKey,AVVideoCodecH264),(AVVideoCompressionPropertiesKey,videoWriterCompressionSettings),(AVVideoWidthKey,videoSize.width),(AVVideoHeightKey,videoSize.height)) var videoWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeVideo,outputSettings: videoWriterSettings) videoWriterInput.expectsMediaDataInRealTime = true videoWriterInput.transform = videoTrack.preferredTransform var videoWriter = AVAssetWriter(URL: outputURL,fileType: AVFileTypeQuickTimeMovie,error: nil) videoWriter.addInput(videoWriterInput) var videoReaderSettings: [String:AnyObject] = [kCVPixelBufferPixelFormatTypeKey:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange] var videoReaderOutput = AVAssetReaderTrackOutput(track: videoTrack,outputSettings: videoReaderSettings) var videoReader = AVAssetReader(asset: videoAsset,error: nil) videoReader.addOutput(videoReaderOutput) //setup audio writer var audioWriterInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio,outputSettings: nil) audioWriterInput.expectsMediaDataInRealTime = false videoWriter.addInput(audioWriterInput) //setup audio reader var audioTrack = videoAsset.tracksWithMediaType(AVMediaTypeAudio)[0] as AVAssetTrack var audioReaderOutput = AVAssetReaderTrackOutput(track: audioTrack,outputSettings: nil) as AVAssetReaderOutput var audioReader = AVAssetReader(asset: videoAsset,error: nil) audioReader.addOutput(audioReaderOutput) videoWriter.startWriting() //start writing from video reader videoReader.startReading() videoWriter.startSessionAtSourceTime(kCMTimeZero) //dispatch_queue_t processingQueue = dispatch_queue_create("processingQueue",nil) var queue = dispatch_queue_create("processingQueue",nil) videoWriterInput.requestMediaDataWhenReadyOnQueue(queue,usingBlock: { () -> Void in println("Export starting") while videoWriterInput.readyForMoreMediaData { var sampleBuffer:CMSampleBufferRef! sampleBuffer = videoReaderOutput.copyNextSampleBuffer() if (videoReader.status == AVAssetReaderStatus.Reading && sampleBuffer != nil) { videoWriterInput.appendSampleBuffer(sampleBuffer) } else { videoWriterInput.markAsFinished() if videoReader.status == AVAssetReaderStatus.Completed { if audioReader.status == AVAssetReaderStatus.Reading || audioReader.status == AVAssetReaderStatus.Completed { } else { audioReader.startReading() videoWriter.startSessionAtSourceTime(kCMTimeZero) var queue2 = dispatch_queue_create("processingQueue2",nil) audioWriterInput.requestMediaDataWhenReadyOnQueue(queue2,usingBlock: { () -> Void in while audioWriterInput.readyForMoreMediaData { var sampleBuffer:CMSampleBufferRef! sampleBuffer = audioReaderOutput.copyNextSampleBuffer() println(sampleBuffer == nil) if (audioReader.status == AVAssetReaderStatus.Reading && sampleBuffer != nil) { audioWriterInput.appendSampleBuffer(sampleBuffer) } else { audioWriterInput.markAsFinished() if (audioReader.status == AVAssetReaderStatus.Completed) { videoWriter.finishWritingWithCompletionHandler({ () -> Void in println("Finished writing video asset.") self.videoUrl = outputURL var data = NSData(contentsOfURL: outputURL)! println("Byte Size After Compression: \(data.length / 1048576) mb") println(videoAsset.playable) //Networking().uploadVideo(data,fileName: "Test2") self.dismissViewControllerAnimated(true,completion: nil) }) break } } } }) break } } }// Second if }//first while })// first block // return }
这是我的UIImagePickerController调用compress方法的代码
func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { // Extract the media type from selection let type = info[UIImagePickerControllerMediaType] as String if (type == kUTTypeMovie) { self.videoUrl = info[UIImagePickerControllerMediaURL] as? NSURL var uploadUrl = NSURL.fileURLWithPath(NSTemporaryDirectory().stringByAppendingPathComponent("captured").stringByAppendingString(".mov")) var data = NSData(contentsOfURL: self.videoUrl!)! println("Size Before Compression: \(data.length / 1048576) mb") self.convertVideo(self.videoUrl!,outputURL: uploadUrl!) // Get the video from the info and set it appropriately. /*self.dismissViewControllerAnimated(true,completion: { () -> Void in //self.next.enabled = true })*/ } }
正如我上面提到的,这个文件大小减少了,但是当我得到文件(它仍然是.mov类型)时,quicktime无法播放. Quicktime最初尝试转换它,但中途失败(打开文件后1-2秒)我甚至测试了AVPlayerController中的视频文件,但它没有提供有关电影的任何信息,它只是一个播放按钮没有蚂蚁加载,没有任何长度只是“ – ”的时间通常在播放器. IE是一个不会播放的损坏的文件.
我确定它与写入资产的设置有关,因为它是视频写作或音频写作我根本不知道.甚至可能是读取导致其破坏的资产.我已经尝试更改变量,并设置不同的键读取和写入,但我没有找到正确的组合,这可以吸收,我可以压缩,但得到一个损坏的文件.我不确定,任何帮助将不胜感激. Pleeeeeeeeease.
解决方法
安德鲁的答案是好的,并作为我在Swift 2.2中实施它的基础.但是,自从他发布以来,有一些事情发生了变化,所以我现在正在使用它,这样可以产生很好的效果.
您可以使用视频文件的现有URL和压缩副本的目标URL来调用此方法.
这是Swift 3.0的答案.
请参阅下面的2.2,虽然它没有更新,以反映改进的风格,因为3.0一个.
extension ViewController: AVCaptureFileOutputRecordingDelegate { func capture(_ captureOutput: AVCaptureFileOutput!,didFinishRecordingToOutputFileAt outputFileURL: URL!,fromConnections connections: [Any]!,error: Error!) { guard let data = NSData(contentsOf: outputFileURL as URL) else { return } print("File size before compression: \(Double(data.length / 1048576)) mb") let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".m4v") compressVideo(inputURL: outputFileURL 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 } } } 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: AVAssetExportPresetMediumQuality) else { handler(nil) return } exportSession.outputURL = outputURL exportSession.outputFileType = AVFileTypeQuickTimeMovie exportSession.shouldOptimizeForNetworkUse = true exportSession.exportAsynchronously { () -> Void in handler(exportSession) } } }
Swift 2.2的答案
let compressedURL = NSURL.fileURLWithPath(NSTemporaryDirectory() + NSUUID().UUIDString + ".m4v") compressVideo(outputFileURL,outputURL: compressedURL) { (session) in switch session.status { case .Unknown: break case .Waiting: break case .Exporting: break case .Completed: let data = NSData(contentsOfURL: compressedURL) print("File size after compression: \(Double(data!.length / 1048576)) mb") case .Failed: break case .Cancelled: break } }
这可以使用switch语句处理所有可能的结果.我把大部分都留空,因为内容会根据应用程序而有所不同.
对于实际的压缩方法,我实现了一个展开,并改变了var.
func compressVideo(inputURL: NSURL,outputURL: NSURL,handler:(session: AVAssetExportSession)-> Void) { let urlAsset = AVURLAsset(URL: inputURL,options: nil) if let exportSession = AVAssetExportSession(asset: urlAsset,presetName: AVAssetExportPresetMediumQuality) { exportSession.outputURL = outputURL exportSession.outputFileType = AVFileTypeQuickTimeMovie exportSession.shouldOptimizeForNetworkUse = true exportSession.exportAsynchronouslyWithCompletionHandler { () -> Void in handler(session: exportSession) } } }
我测试了几个视频,并看到一些非常显着的减少(例如:20 MB变成500k).