你得到一個空數組,當你做
NSArray *outputs = self.mainPlayer.currentItem.outputs;
因爲AVPlayerItemVideoOutput
對象需要第一
NSDictionary *settings = @{(id)kCVPixelBufferPixelFormatTypeKey : [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]};
self.videoOutput = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:settings];
[playerItem addOutput:self.videoOutput];
,然後在AVPlayerItem
狀態爲AVPlayerStatusReadyToPlay
,你可以捕捉當前要添加使用copyPixelBufferForItemTime:itemTimeForDisplay
的框架。對於這一點,你需要創建AVPlayer
對象和觀察者添加到AVPlayerItem
狀態屬性
self.player = [AVPlayer playerWithPlayerItem:playerItem];
[self.player.currentItem addObserver:self forKeyPath:@"status" options:0 context:NULL];
,然後在回調函數
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (self.player.currentItem.status == AVPlayerStatusReadyToPlay)
{
CMTime currentTime = self.player.currentItem.currentTime;
CVPixelBufferRef buffer = [self.videoOutput copyPixelBufferForItemTime:currentTime itemTimeForDisplay:nil];
CIImage *ciImage = [CIImage imageWithCVPixelBuffer:buffer];
UIImage *image = [UIImage imageWithCIImage:ciImage];
// use `image`
}
}
如果你只需要捕獲縮略圖,你不首先不必播放視頻,您可以使用我創建的簡單實用程序遵循此邏輯。 (https://github.com/acotilla91/ACThumbnailGenerator)
如何使用:
double bitRate = 1000000; // force video bit rate (can be use to cap video quality and improve performance). Pass 0 to use default bit rate.
self.thumbnailGenerator = [[ACThumbnailGenerator alloc] initWithPreferredBitRate:bitRate];
NSURL *videoURL = [NSURL URLWithString:@"http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8"];
int position = 10; // video position (in seconds) from where thumbnail should be extracted. Always pass 0 for live streams.
[self.thumbnailGenerator loadImageFrom:videoURL position:position withCompletionBlock:^(UIImage *image) {
// use `image`
}];
希望它能幫助。