2013-10-17 93 views
9

当使用AVPlayer播放来自url的音频时,它将在例如从WiFi断开连接时停止播放。AVPlayer:如何处理网络中断

[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 并重新开始播放?

+0

不知道有关播放只有音频的时候,但对于视频,听'AVPlayerItemFailedToPlayToEndTimeNotification'在其他答案建议。另外,对于HLS实时视频流,我们需要重新创建AVPlayerItem并将其设置为AVPlayer。只是调用'play()',寻找等似乎不适合我们。现在寻找更好的解决方案,但这是目前我所知道的最好的解决方案。如果avplayerite的'.status'失败,我们也需要重新创建它(我的假设)。 – Jonny

回答

11

为了处理网络更改,您必须添加一个观察者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 ... 
} 
0

0xced在斯威夫特3回答:

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 

}