有時我們需要在界面上顯示視頻的縮略圖,這樣用戶不用點開也能大概了解到視頻的內容。下面分別演示如何獲取本地視頻,以及網絡在線視頻的視頻截圖。
樣例的效果圖如下,將獲取到的截圖(視頻開始部分)顯示在 imageView 中。
1,獲取本地視頻截圖
import UIKit
import AVFoundation
import MobileCoreServices
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//獲取本地視頻
let filePath = NSBundle.mainBundle().pathForResource("hangge", ofType: "m4v")
let videoURL = NSURL(fileURLWithPath: filePath!)
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 imageRef:CGImageRef = try! generator.copyCGImageAtTime(time, actualTime: &actualTime)
let frameImg = UIImage(CGImage: imageRef)
//顯示截圖
self.imageView.image = frameImg
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
2,獲取網絡視頻截圖
由於網絡請求比較耗時,所以我們把獲取在線視頻的相關代碼寫在異步線程裡。
import UIKit
import AVFoundation
import MobileCoreServices
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//異步獲取網絡視頻
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), {
//獲取網絡視頻
let url = "http://www.hangge.com/hangge.mp4"
let videoURL = NSURL(string: url)!
let avAsset = AVURLAsset(URL: videoURL)
//生成視頻截圖
let generator = AVAssetImageGenerator(asset: avAsset)
generator.appliesPreferredTrackTransform = true
let time = CMTimeMakeWithSeconds(0.0,600)
var actualTime:CMTime = CMTimeMake(0,0)
let imageRef:CGImageRef = try! generator.copyCGImageAtTime(time, actualTime: &actualTime)
let frameImg = UIImage(CGImage: imageRef)
//在主線程中顯示截圖
dispatch_async(dispatch_get_main_queue(), {
self.imageView.image = frameImg
})
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}