有時我們需要在介面上顯示視頻的縮圖,這樣使用者不用點開也能大概瞭解到視頻的內容。下面分別示範如何擷取本地視頻,以及網路線上視頻的視頻截圖。
範例的效果圖如下,將擷取到的截圖(視頻開始部分)顯示在 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()
}
}