在Swift 5中,可以使用以下方法来缩小视频文件大小:
import AVFoundation
func compressVideo(inputURL: URL, outputURL: URL, completion: @escaping (URL?, Error?) -> Void) {
let asset = AVAsset(url: inputURL)
guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetMediumQuality) else {
completion(nil, NSError(domain: "com.example", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to create AVAssetExportSession"]))
return
}
exportSession.outputURL = outputURL
exportSession.outputFileType = .mp4
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously {
switch exportSession.status {
case .completed:
completion(outputURL, nil)
case .failed:
completion(nil, exportSession.error)
case .cancelled:
completion(nil, NSError(domain: "com.example", code: 0, userInfo: [NSLocalizedDescriptionKey: "Export cancelled"]))
default:
break
}
}
}
// 使用示例
let inputURL = URL(fileURLWithPath: "path/to/input/video.mov")
let outputURL = URL(fileURLWithPath: "path/to/output/compressed-video.mp4")
compressVideo(inputURL: inputURL, outputURL: outputURL) { (outputURL, error) in
if let error = error {
print("Failed to compress video: \(error.localizedDescription)")
} else if let outputURL = outputURL {
print("Video compressed successfully. Output URL: \(outputURL)")
}
}
import AVFoundation
func resizeVideo(inputURL: URL, outputURL: URL, targetSize: CGSize, targetFrameRate: Int32, completion: @escaping (URL?, Error?) -> Void) {
let asset = AVAsset(url: inputURL)
guard let videoTrack = asset.tracks(withMediaType: .video).first else {
completion(nil, NSError(domain: "com.example", code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to get video track"]))
return
}
let composition = AVMutableComposition()
let compositionVideoTrack = composition.addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid)
do {
try compositionVideoTrack?.insertTimeRange(CMTimeRange(start: .zero, duration: asset.duration), of: videoTrack, at: .zero)
} catch {
completion(nil, error)
return
}
let videoSettings = [
AVVideoCodecKey: AVVideoCodecType.h264,
AVVideoWidthKey: targetSize.width,
AVVideoHeightKey: targetSize.height,
AVVideoCompressionPropertiesKey: [
AVVideoAverageBitRateKey: targetSize.width * targetSize.height * targetFrameRate
]
] as [String : Any]
let writer = try? AVAssetWriter(outputURL: outputURL, fileType: .mp4)
let writerInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
writer?.add(writerInput)
writer?.startWriting()
writer?.startSession(atSourceTime: .zero)
let processingQueue = DispatchQueue(label: "com.example.processingqueue")
writerInput.requestMediaDataWhenReady(on: processingQueue) {
while writerInput.isReadyForMoreMediaData {
let sampleBuffer = videoTrackOutput.copyNextSampleBuffer()
if sampleBuffer != nil {
writerInput.append(sampleBuffer!)
} else {
writerInput.markAsFinished()
writer?.finishWriting(completionHandler: {
if writer?.status == .completed {
completion(outputURL, nil)
} else {
completion(nil, writer?.error)
}
})
break
}
}
}
}
// 使用示例
let inputURL = URL(fileURLWithPath: "path/to/input/video.mov")
let outputURL = URL(fileURLWithPath: "path/to/output/resized-video.mp4")
let targetSize = CGSize(width: 640, height: 480)
let targetFrameRate: Int32 = 30
resizeVideo(inputURL: inputURL, outputURL: outputURL, targetSize: targetSize, targetFrameRate: targetFrameRate) { (outputURL, error) in
if let error = error {
print("Failed to resize video: \(error.localizedDescription)")
} else if let outputURL = outputURL {
print("Video resized successfully. Output URL: \(outputURL)")
}
}
这些方法可以帮助你在Swift 5中缩小视频文件大小。请注意,这些示例代码仅涵盖了基本的视频压缩和调整分辨率/帧率的功能,实际应用中可能需要根据具体需求进行更多的优化和调整。
腾讯云相关产品和产品介绍链接地址:
请注意,以上产品仅作为示例,实际选择产品时应根据具体需求和场景进行评估和选择。
领取专属 10元无门槛券
手把手带您无忧上云