.mov格式是Apple公司开发的一种音频,视频的格式,由苹果系统的相机录制出来的视频都是以.mov格式进行存储的。最近要搞本地相册视频上传,如果要是以.mov格式上传的话,安卓端播放起来有可能会出现麻烦,所以就想在视频上传之前将其转换一下格式,统一的转换成.mp4格式,下面就是实现的代码:Swift .mov转.mp4的写法,记录下来跟大家分享,也为自己做笔记。
//视频转换格式.mov 转成 .mp4
//方法中sourceUrl参数为.mov的URL数据
class func movFileTransformToMp4WithSourceUrl(sourceUrl: URL) {
//以当前时间来为文件命名
let date = Date()
let formatter = DateFormatter.init()
formatter.dateFormat = "yyyyMMddHHmmss"
let fileName = formatter.string(from: date) + ".mp4"
//保存址沙盒路径
let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
let videoSandBoxPath = (docPath as String) + "/ablumVideo" + fileName
print(videoSandBoxPath)
//转码配置
let avAsset = AVURLAsset.init(url: sourceUrl, options: nil)
//取视频的时间并处理,用于上传
let time = avAsset.duration
let number = Float(CMTimeGetSeconds(time)) - Float(Int(CMTimeGetSeconds(time)))
let totalSecond = number > 0.5 ? Int(CMTimeGetSeconds(time)) + 1 : Int(CMTimeGetSeconds(time))
let photoId = String(totalSecond)
let exportSession = AVAssetExportSession.init(asset: avAsset, presetName: AVAssetExportPresetMediumQuality)
exportSession?.shouldOptimizeForNetworkUse = true
exportSession?.outputURL = URL.init(fileURLWithPath: videoSandBoxPath)
exportSession?.outputFileType = AVFileTypeMPEG4 //控制转码的格式
exportSession?.exportAsynchronously(completionHandler: {
if exportSession?.status == AVAssetExportSessionStatus.failed {
print("转码失败")
}
if exportSession?.status == AVAssetExportSessionStatus.completed {
print("转码成功")
//转码成功后就可以通过dataurl获取视频的Data用于上传了
let dataurl = URL.init(fileURLWithPath: videoSandBoxPath)
//上传视频的话是需要同时上传一张视频封面图片的,这里附带一个获取视频封面截图的方法,方法实现在下方
let image = getVideoCropPicture(videoUrl: sourceUrl)
}
})
}
获取视频封面截图
class func getVideoCropPicture(videoUrl: URL) -> UIImage {
let avAsset = AVAsset(url: videoUrl)
let generator = AVAssetImageGenerator(asset: avAsset)
generator.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(0.0, 600)
var actualTime: CMTime = CMTimeMake(0, 0)
let imageP = try? generator.copyCGImage(at: time, actualTime: &actualTime)
let image = UIImage.init(cgImage: imageP!)
return image
}
最后说一句废话 不要忘了要引入 AVFoundation 框架
import AVFoundation