如何处理网络中断

如何处理网络中断

本文介绍了AVPlayer:如何处理网络中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用AVPlayer播放来自网址的音频时,
会停止播放,例如断开与wifi的连接。

When using AVPlayer to play audio from an url it willdiscontinue to play when for example disconnecting from wifi.

[player play];

不恢复AVPlayer

Does not resume the AVPlayer

player.rate // Value is 1.0

player.currentItem.isPlaybackLikelyToKeepUp // Value is YES

player.status // Value is AVPlayerStatusReadyToPlay

player.error // Value is nil

但播放器没有播放任何音频。

But the player is not playing any audio.

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

How do I handle a disconnect from AVPlayer, for reconnecting the AVPlayerand start playing again?

推荐答案

为了处理网络变化,你必须为添加观察者AVPlayerItemFailedToPlayToEndTimeNotification

In order to handle network changes, you have to add an observer for 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 ...
}

这篇关于AVPlayer:如何处理网络中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 14:34