在AVPlayer中播放与坏互联网的流

时间:2014-04-02 13:48:50

标签: ios streaming avfoundation avplayer

当AVPlayer播放来自网络流的资源时,它会在到达下载内容的末尾时暂停。

所以,我的问题是,如何知道它因网络不良而停止了?如何在下载之后播放它,比方说,接下来10秒的资产?

3 个答案:

答案 0 :(得分:6)

您可以在AVPlayer获取空缓冲区时添加观察者:

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

还有一个观察者,这样你就可以知道AVPlayer何时进行了足够的缓冲以便跟上:

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

然后在KVO回调中检查一下:

- (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 :(得分:3)

对于swift

if (conditionA1() ||
    conditionA2() && conditionA3() ||
    ... &&
    conditionAN()) {
    functionA();
}
else if (conditionB1() ||
         conditionB2() && conditionB3() ||
         ... &&
         conditionBN() {
    functionB();
}
...
else if (conditionZ1() ||
         conditionZ2() && conditionZ3() ||
         ... && conditionZN()) {
    functionZ();
}

答案 2 :(得分:0)

Swift 4 改变了KVO的方式。我们不是单独添加观察者和函数,而是在一个地方使用闭包(块)。

var observers: [NSKeyValueObservation]?
let playerItem = AVPlayerItem(url: YOUR_URL)

let emptyObserver = playerItem.observe(\.isPlaybackBufferEmpty) {
                        [weak self] (object, observedChange) in
                        // show a progress bar 
                        print("isPlaybackBufferEmpty")
                    }

let keepUpObserver = playerItem.observe(\.playbackLikelyToKeepUp) {
                        [weak self] (object, observedChange) in
                        // hide progress bar and keep going 
                        print("playbackLikelyToKeepUp")
                    }

self.observers = [emptyObserver, keepUpObserver]