当使用AVPlayer从网址播放音频时,它将停止播放,例如断开与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
但播放器没有播放任何音频。
如何处理与AVPlayer的断开连接,重新连接AVPlayer并重新开始播放?
为了处理网络更改,您必须为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 ...
}
你应该为AVPlayerItemPlaybackStalledNotification添加观察者。
AVPlayerItemFailedToPlayToEndTimeNotification在这个问题上没有价值。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackStalled:) name:AVPlayerItemPlaybackStalledNotification object:trackItem];
正如文档所说,如果必要的流媒体不能通过网络及时传送,基于文件的播放就不会继续。
通知的对象是AVPlayerItem实例,其回放无法继续,因为必要的流媒体未通过网络及时传送。一旦传送了足够数量的数据,就继续播放流媒体。基于文件的播放不会继续。
这解释了为什么AVPlayer可以在网络切换后恢复HLS流,但是如果我使用AVPlayer播放基于文件的TuneIn资源则无法做到这一点。
然后答案变得简单。
- (void)playbackStalled:(NSNotification *)notification {
if ([self isFileBased:streamUri]) {
// Restart playback
NSURL *url = [NSURL URLWithString:streamUri];
AVPlayerItem *trackItem = [AVPlayerItem playerItemWithURL:url];
AVPlayer *mediaPlayer = [AVPlayer playerWithPlayerItem:trackItem];
[self registerObservers:trackItem player:mediaPlayer];
[mediaPlayer play];
}
}
对于Swift 3/4,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
}