简体   繁体   中英

Using AVPlayer for streaming is slow

I use AVPlayer for streaming mp3 file from the internet and it works really slow. Using profiler I found out, that it downloads entire file at first, and then starts playing. Is there any workaround for this?

Right now, I'm using this code

if let player = player {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)

    let item = AVPlayerItem(url: url)

    player.replaceCurrentItem(with: item)
} else {
    player = AVPlayer(url: url)
}
player?.play()

Things I've tried:

  • move player?.play() to an observer, attached to status property of the item
  • play around with properties preferredForwardBufferDuration and preferredPeakBitRate

All the time the result is downloading a whole audio file and only then start of playing.

Please note, the issue is - player starts to play ONLY after the whole file was downloaded, while I want it to stream mp3.

要立即播放,您可以尝试设置

player.automaticallyWaitsToMinimizeStalling = false

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM