Sometimes we need to display a thumbnail image of the video in the interface so that the user can probably get a sense of the content without having to click. Here's how to get a local video, as well as a video screenshot of a network online video.
The sample effect is shown below, and the captured screenshot (the beginning of the video) is displayed in the ImageView.
1, get the local video screenshot
Import Uikit
Import Avfoundation
Import Mobilecoreservices
Class Viewcontroller:uiviewcontroller {
@IBOutlet weak var imageview:uiimageview!
Override Func Viewdidload () {
Super.viewdidload ()
Get local video
Let FilePath = Nsbundle.mainbundle (). Pathforresource ("Hangge", OfType: "M4V")
Let Videourl = Nsurl (fileurlwithpath:filepath!)
Let Avasset = Avasset (Url:videourl)
Generate a video screenshot
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)
Show screenshots
Self.imageView.image = frameimg
}
Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}
2, get the network video screenshot
Because the network request is time-consuming, we write the relevant code to get the online video in the asynchronous thread.
Import Uikit
Import Avfoundation
Import Mobilecoreservices
Class Viewcontroller:uiviewcontroller {
@IBOutlet weak var imageview:uiimageview!
Override Func Viewdidload () {
Super.viewdidload ()
Get Network Video asynchronously
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default,0), {
Get Network Video
Let URL = "Http://www.hangge.com/hangge.mp4"
Let Videourl = Nsurl (string:url)!
Let Avasset = Avurlasset (Url:videourl)
Generate a video screenshot
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)
Show screenshots in main thread
Dispatch_async (Dispatch_get_main_queue (), {
Self.imageView.image = frameimg
})
})
}
Override Func didreceivememorywarning () {
Super.didreceivememorywarning ()
}
}