AVPlayer:如何处理networking中断

当使用AVPlayer从一个url播放audio时,它将停止播放时,例如从WiFi断开连接。

[player play]; 

不要恢复AVPlayer

 player.rate // Value is 1.0 player.currentItem.isPlaybackLikelyToKeepUp // Value is YES player.status // Value is AVPlayerStatusReadyToPlay player.error // Value is nil 

但播放器不播放任何audio。

如何处理与AVPlayer的断开连接,重新连接AVPlayer并重新开始播放?

为了处理networking更改,您必须添加一个观察者AVPlayerItemFailedToPlayToEndTimeNotification

 - (void) playURL:(NSURL *)url { AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemFailedToPlayToEndTime:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:playerItem]; self.player = [AVPlayer playerWithPlayerItem:playerItem]; [self.player play]; } - (void) playerItemFailedToPlayToEndTime:(NSNotification *)notification { NSError *error = notification.userInfo[AVPlayerItemFailedToPlayToEndTimeErrorKey]; // Handle error ... } 

在Swift 3中的0xced的答案:

 var playerItem: AVPlayerItem? var player: AVPlayer? func instantiatePlayer(_ url: URL) { self.playerItem = AVPlayerItem(url: url) self.player = AVPlayer(playerItem: self.playerItem) NotificationCenter.default.addObserver(self, selector: #selector(playerItemFailedToPlay(_:)), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil) } func playerItemFailedToPlay(_ notification: Notification) { let error = notification.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error }