前言: 看完了使用MPMoviePlayerController播放在線視頻,在實際應用中有時候需要獲取視頻的縮略圖,我們來看看如何截取指定時間內的視頻縮略圖。
一 使用MPMoviePlayerController自帶的方法
- (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes timeOption:(MPMovieTimeOption)option NS_AVAILABLE_IOS(3_2);
/**
* 視頻截圖
*/
- (void)getMovieThumImage
{
[self.moviePlayer requestThumbnailImagesAtTimes:@[@(1.0),@(5.0)] //設置截圖時間點 1s和5s的時候
timeOption:MPMovieTimeOptionNearestKeyFrame];
}
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(thumImageGet:)
name:MPMoviePlayerThumbnailImageRequestDidFinishNotification //視頻縮略圖截取成功時調用
object:nil];
/**
* 截圖完成,每截取一張,會調取一次
*
* @param noti <#noti description#>
*/
- (void)thumImageGet:(NSNotification *)noti
{
UIImage *thumImage = [[noti userInfo] objectForKey:MPMoviePlayerThumbnailImageKey];
UIImageWriteToSavedPhotosAlbum(thumImage, nil, nil, nil);
}
#import
- (void)assetGetThumImage:(CGFloat)second { AVURLAsset *urlSet = [AVURLAsset assetWithURL:[self url]]; AVAssetImageGenerator *imageGenerator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet]; NSError *error = nil; CMTime time = CMTimeMake(second,10);//縮略圖創建時間 CMTime是表示電影時間信息的結構體,第一個參數表示是視頻第幾秒,第二個參數表示每秒幀數.(如果要活的某一秒的第幾幀可以使用CMTimeMake方法) CMTime actucalTime; //縮略圖實際生成的時間 CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:&actucalTime error:&error]; if (error) { NSLog(@截取視頻圖片失敗:%@,error.localizedDescription); } CMTimeShow(actucalTime); UIImage *image = [UIImage imageWithCGImage:cgImage]; UIImageWriteToSavedPhotosAlbum(image,nil, nil,nil); CGImageRelease(cgImage); NSLog(@視頻截取成功); }