前言
最近做項(xiàng)目,使用到了PHAseet,因?yàn)锳LAsset已經(jīng)廢棄了.實(shí)話說(shuō),PHAseet現(xiàn)在比ALAsset麻煩,獲取地址路徑就很惡心,總之,一點(diǎn)點(diǎn)也是趟過(guò)來(lái)了,做個(gè)記錄,以后自己別忘了.
獲取圖片,獲取視頻首幀
let option = PHImageRequestOptions()
option.isNetworkAccessAllowed = true //允許下載iCloud的圖片
option.resizeMode = .fast
option.deliveryMode = .fastFormat
PHImageManager.default().requestImage(for: asset,
targetSize: self.bounds.size,
contentMode: .aspectFill,
options: option)
{ (image, nil) in
//image就是圖片
}
獲取視頻
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .automatic
PHImageManager.default().requestPlayerItem(forVideo:asset, options: options, resultHandler: { playerItem, info in
guard self.playerLayer == nil else { return }
//播放視頻
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
playerLayer.frame = self.layer.bounds
self.contentView.layer.insertSublayer(playerLayer, below: self.palyBtn.layer)
player.play()
self.playerLayer = playerLayer
})
注意事項(xiàng)
使用的時(shí)候,盡量將option.isNetworkAccessAllowed = true
打開(kāi), 允許下載iCloud的圖片和視頻,否則會(huì)照成crash.這塊當(dāng)時(shí)給我弄的很無(wú)奈,因?yàn)槲液脦讉€(gè)地方都上傳圖片,改了好幾遍.
將PHAsset轉(zhuǎn)化為視頻的NSData
我自己封裝了一個(gè)簡(jiǎn)單的類,代碼入下
import UIKit
import Photos
class XXVideoCompression: NSObject {
public func compressVideo(_ exportSession:AVAssetExportSession? , completion: @escaping (_ data: Data)-> Void) {
let uuu = self.compressedUrl()
exportSession?.outputURL = URL.init(fileURLWithPath: uuu)
exportSession?.outputFileType = .mp4
exportSession?.shouldOptimizeForNetworkUse = true;
if let assetTime = exportSession?.asset.duration {
let duration = CMTimeGetSeconds(assetTime)
print("視頻時(shí)長(zhǎng) \(duration)");
}
exportSession?.exportAsynchronously(completionHandler: {
switch exportSession?.status{
case .failed?:
print("失敗...\(String(describing: exportSession?.error?.localizedDescription))")
completion(Data())
break
case .cancelled?:
print("取消")
completion(Data())
break;
case .completed?:
print("轉(zhuǎn)碼成功")
do {
let data = try Data.init(contentsOf: URL.init(fileURLWithPath: uuu), options: Data.ReadingOptions.init())
let mp4Path = URL.init(fileURLWithPath: uuu)
let size = self.fileSize(url: mp4Path)
print("視頻時(shí)長(zhǎng)\(size)")
completion(data)
} catch let error {
print("失敗 \(error)")
completion(Data())
}
break;
default:
print("..")
completion(Data())
break;
}
})
}
//保存壓縮
func compressedUrl() -> String {
let string = NSHomeDirectory() + "/Documents/\(Date().timeIntervalSince1970).mp4"
return string//URL.init(fileURLWithPath: string)
}
//計(jì)算視頻大小
func fileSize(url:URL) -> CGFloat {
return CGFloat(NSData.init(contentsOf: url)?.length ?? 0 )/// 1024 / 1024
}
//獲取視頻首幀
func imageWithVideoUrl(mediaModel:HEPhotoAsset,completion: @escaping ( _ image:UIImage) -> Void) {
let option = PHImageRequestOptions()
option.isNetworkAccessAllowed = true
option.resizeMode = .fast
option.deliveryMode = .fastFormat
PHImageManager.default().requestImage(for: mediaModel.asset,
targetSize:PHImageManagerMaximumSize,
contentMode: .aspectFill,
options: option )
{ (image, info) in
completion(image ?? UIImage())
}
}
}
具體使用如下:
//
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .automatic
PHImageManager.default().requestExportSession(forVideo: mediaModel.asset, options: options, exportPreset: AVAssetExportPresetMediumQuality) { (exportSession, info) in
//將asset轉(zhuǎn)換為AVAssetExportSession對(duì)象,用AVAssetExportSession轉(zhuǎn)化為Data
XXVideoCompression().compressVideo(exportSession, completion: { (data) in
if data.count > 0 {//做判斷,判斷是否轉(zhuǎn)化成功
//進(jìn)行視頻上傳
}
}
}
具體問(wèn)題具體分析,使用過(guò)程中,總會(huì)遇到各種各樣的問(wèn)題,但是只要有耐心,總會(huì)一點(diǎn)點(diǎn)解決的.歡迎各位留言,提問(wèn).
如果我的文章,對(duì)你有幫助,請(qǐng)給我一個(gè)??哦~~!