Swift - 压缩视频文件 [英] Swift - Compressing video files
本文介绍了Swift - 压缩视频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,目前我正在使用它来压缩视频:
So, at the moment I am using this to compress video:
func compressVideo(inputURL: NSURL, outputURL: NSURL, handler:(session: AVAssetExportSession)-> Void)
{
let urlAsset = AVURLAsset(URL: inputURL, options: nil)
let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality)
exportSession!.outputURL = outputURL
exportSession!.outputFileType = AVFileTypeQuickTimeMovie
exportSession!.shouldOptimizeForNetworkUse = true
exportSession!.exportAsynchronouslyWithCompletionHandler { () -> Void in
handler(session: exportSession!)
}
}
当我在 2 秒内录制视频时,大小为 4,3 MB,当我在 6 秒内录制视频时,文件大小为 9,3 MB.
When I recorded a video in 2 seconds, the size was 4,3 MB and when I recorded a video in 6 seconds the file size was 9,3 MB.
有什么减小尺寸的技巧吗?
Any tips to reduce the size?
推荐答案
此扩展侧重于将其导出为较低质量的设置(在本例中为中等)并使用 mp4
容器,而不是 mp4
iOS 青睐的 code>mov 容器.这可能会导致质量下降,但您可以尝试使用更高的输出设置和不同的格式来微调输出.
This extension focuses on exporting it to a lower quality setting (in this case Medium) and uses an mp4
container, over the mov
container favored by iOS. This can result in a loss of quality, but you can experiment with higher output settings and different formats as you work to fine tune your output.
extension PreviewVideoViewController: AVCaptureFileOutputRecordingDelegate {
func fileOutput(_ output: AVCaptureFileOutput,
didFinishRecordingTo outputFileURL: URL,
from connections: [AVCaptureConnection],
error: Error?) {
guard let data = try? Data(contentsOf: outputFileURL) else {
return
}
print("File size before compression: (Double(data.count / 1048576)) mb")
let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + UUID().uuidString + ".mp4")
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 = try? Data(contentsOf: compressedURL) else {
return
}
print("File size after compression: (Double(compressedData.count / 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 = .mp4
exportSession.exportAsynchronously {
handler(exportSession)
}
}
}
这篇关于Swift - 压缩视频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文