在AVPlayer中播放与糟糕的互联网stream

AVPlayer播放来自networkingstream的资源时,会在下载内容到达时暂停。

所以,我的问题是,如何知道,它因为networking不好而停止? 如何在下载之后播放它,比如说,下一个10秒的资产?

你可以添加一个观察者,当AVPlayer的空缓冲区:

[[self.tracksPlayer currentItem] addObserver:self forKeyPath:@"playbackBufferEmpty" options:NSKeyValueObservingOptionNew context:nil]; 

还有一位观察者,所以你可以知道什么时候AVPlayer足够缓冲:

 [[self.tracksPlayer currentItem] addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil]; 

然后在你的KVOcallback中检查一下:

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object == [self.tracksPlayer currentItem] && [keyPath isEqualToString:@"playbackBufferEmpty"]) { if ([self.tracksPlayer currentItem].playbackBufferEmpty) { NSLog(@"Buffer Empty"); } } else if (object == [self.tracksPlayer currentItem] && [keyPath isEqualToString:@"playbackLikelyToKeepUp"]) { if ([self.tracksPlayer currentItem].playbackLikelyToKeepUp) { NSLog(@"LikelyToKeepUp"); } } } 

为了迅速

 1) let playbackLikelyToKeepUpContext = UnsafeMutablePointer<(Void)>(nil) or let playbackLikelyToKeepUpContext = UnsafeMutablePointer<(Void)>() 2) //Add Observer player.addObserver(self, forKeyPath: "currentItem.playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.New, context: playbackLikelyToKeepUpContext) player.play() 3) //Add observer override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard keyPath != nil else { // a safety precaution super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) return } if (context == playbackLikelyToKeepUpContext) { if (player.currentItem!.playbackLikelyToKeepUp) { player.play() Utilities.hideHUD(self.view) } else { Utilities.showHUD(self.view) } } } 4) // Remove Observer override func viewDidDisappear(animated: Bool) { player.removeObserver(self, forKeyPath: "currentItem.playbackLikelyToKeepUp") }