Alfred Zien Alfred Zien - 4 months ago 97
iOS Question

Playing stream with bad internet in AVPlayer

When AVPlayer plays an asset that comes from network stream, it pauses when reaches the end of downloaded content.

So, my question is, how to know, that it stopped because of bad network? And how to play it after it downloads, let’s say, next 10 seconds of asset?

Answer

You can add an observer to when the AVPlayer gets empty buffer:

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

And an observer so you can know when the AVPlayer buffered enough to keep up:

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

Then just check for that in your KVO callback:

- (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");
      }
   }
}
Comments