2013-10-17 86 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 

}