用 MPMoviePlayerController 播放線上影片之後,常會需要取得某個時間點的預覽圖。以下提供兩種做法:一種依賴播放器本身,另一種用 AVFoundation 的 AVAssetImageGenerator,後者更通用。
- (void)requestThumbnailImagesAtTimes:(NSArray *)playbackTimes
timeOption:(MPMovieTimeOption)option;
使用範例:
// 擷取 1 秒與 5 秒處的畫面
- (void)getMovieThumbImage {
[self.moviePlayer requestThumbnailImagesAtTimes:@[@(1.0), @(5.0)]
timeOption:MPMovieTimeOptionNearestKeyFrame];
}
擷取完成後會收到通知:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(thumImageGet:)
name:MPMoviePlayerThumbnailImageRequestDidFinishNotification
object:nil];
// 每擷取一張就會回呼一次
- (void)thumImageGet:(NSNotification *)noti {
UIImage *thumImage = [[noti userInfo] objectForKey:MPMoviePlayerThumbnailImageKey];
UIImageWriteToSavedPhotosAlbum(thumImage, nil, nil, nil);
}
這個方法的缺點很明顯:MPMoviePlayerController 從 iOS 9 起已被標記為棄用,不適合再用在新專案。
步驟:
AVURLAsset 物件(此類別主要用於讀取媒體資訊,包含影片與聲音)。AVURLAsset 建立 AVAssetImageGenerator。copyCGImageAtTime:actualTime:error: 取得指定時間點的畫面。#import <AVFoundation/AVFoundation.h>
- (void)assetGetThumbImage:(CGFloat)second {
AVURLAsset *urlSet = [AVURLAsset assetWithURL:[self url]];
AVAssetImageGenerator *imageGenerator =
[AVAssetImageGenerator assetImageGeneratorWithAsset:urlSet];
// CMTime 是描述影片時間的結構:
// 第一個參數是第幾秒,第二個參數是每秒幀數
CMTime time = CMTimeMake(second, 10);
CMTime actualTime;
NSError *error = nil;
CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time
actualTime:&actualTime
error:&error];
if (error) {
NSLog(@"擷取影片畫面失敗:%@", error.localizedDescription);
return;
}
CMTimeShow(actualTime);
UIImage *image = [UIImage imageWithCGImage:cgImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
// CGImageRef 是 C 核心物件,必須手動釋放
CGImageRelease(cgImage);
NSLog(@"擷取成功");
}
copyCGImageAtTime: 開頭有 copy,代表所有權轉移給呼叫方,因此務必 CGImageRelease,否則會持續洩漏記憶體。generateCGImagesAsynchronouslyForTimes:completionHandler: 搭配 AVAssetImageGenerator 的 maximumSize 屬性會更有效率。NSPhotoLibraryAddUsageDescription 的用途說明,否則在 iOS 10 以上會直接 crash。