.mov格式是Apple公司開(kāi)發(fā)的一種音頻河劝,視頻的格式赎瞎,由蘋(píng)果系統(tǒng)的相機(jī)錄制出來(lái)的視頻都是以.mov格式進(jìn)行存儲(chǔ)的。最近要搞本地相冊(cè)視頻上傳务甥,如果要是以.mov格式上傳的話,安卓端播放起來(lái)有可能會(huì)出現(xiàn)麻煩态辛,所以就想在視頻上傳之前將其轉(zhuǎn)換一下格式,統(tǒng)一的轉(zhuǎn)換成.mp4格式挺尿,下面就是實(shí)現(xiàn)的代碼:Swift .mov轉(zhuǎn).mp4的寫(xiě)法奏黑,記錄下來(lái)跟大家分享,也為自己做筆記票髓。
//視頻轉(zhuǎn)換格式.mov 轉(zhuǎn)成 .mp4
//方法中sourceUrl參數(shù)為.mov的URL數(shù)據(jù)
class func movFileTransformToMp4WithSourceUrl(sourceUrl: URL) {
//以當(dāng)前時(shí)間來(lái)為文件命名
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)
//轉(zhuǎn)碼配置
let avAsset = AVURLAsset.init(url: sourceUrl, options: nil)
//取視頻的時(shí)間并處理攀涵,用于上傳
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 //控制轉(zhuǎn)碼的格式
exportSession?.exportAsynchronously(completionHandler: {
if exportSession?.status == AVAssetExportSessionStatus.failed {
print("轉(zhuǎn)碼失敗")
}
if exportSession?.status == AVAssetExportSessionStatus.completed {
print("轉(zhuǎn)碼成功")
//轉(zhuǎn)碼成功后就可以通過(guò)dataurl獲取視頻的Data用于上傳了
let dataurl = URL.init(fileURLWithPath: videoSandBoxPath)
//上傳視頻的話是需要同時(shí)上傳一張視頻封面圖片的,這里附帶一個(gè)獲取視頻封面截圖的方法洽沟,方法實(shí)現(xiàn)在下方
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
}
最后說(shuō)一句廢話 不要忘了要引入 AVFoundation 框架
import AVFoundation