2015-10-21 37 views
2

所以我有一個AVPlayer,玩從.m3u8視頻和實時流什麼我發現搜索它看起來就像你不能用AVAssetImageGenerator進行屏幕截圖,而是應該使用AVPlayerItemVideoOutput和AVPlayer streaming .m3u8的UIImage幀在給定的時間?

- (CVPixelBufferRef)copyPixelBufferForItemTime:(CMTime)itemTime itemTimeForDisplay:(CMTime *)outItemTimeForDisplay 

但是當我嘗試從AVPlayer獲取輸出時。

NSArray *outputs = self.mainPlayer.currentItem.outputs; 

我得到一個空數組。

視頻播放還好。最終我想要的是這樣的一種方法。

-(UIImage *)frameFor:(CMTime)time; 

在某些時候,在視圖上的CALayer必須得到這個圖像數據,所以他們必須搶在某一點的方式。我嘗試捕獲我的AVPLayerLayer附加到的CALayer,但除了空白的視圖顏色(明亮的粉紅色,以確保其返回的東西)之外,我沒有得到任何東西。他們必須以某種方式獲取這些數據。

回答

0

你得到一個空數組,當你做

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`    

}]; 

希望它能幫助。