简体   繁体   中英

How to handle network interruption in AVPlayer

I have using reachability to determine network change but once I determine I am trying to reload item but it is not working

// Check if the playback could keep up after a network interruption
private func checkNetworkInterruption() {
    guard
        let item = playerItem,
        !item.isPlaybackLikelyToKeepUp,
        reachability?.connection != .unavailable else { return }

    self.player?.pause()

    // Wait 1 sec to recheck and make sure the reload is needed
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
        if !item.isPlaybackLikelyToKeepUp {
            self.reloadItem()
        }
        self.isPlaying ? self.playSong() : self.player?.pause()
    }
}

private func reloadItem() { player?.replaceCurrentItem(with: nil) player?.replaceCurrentItem(with: playerItem) }

AVPlayer can handle the network interrupts by itself, when network fails, the video is paused and keep in buffering status when network is stable, the video is resumed.

but if you need to handle the network interruption, you can try:

private func checkNetworkInterruption() {
    guard
        let item = playerItem,
        !item.isPlaybackLikelyToKeepUp,
        reachability?.connection != .unavailable else { return }

    self.player?.pause()

    // Wait 1 sec to recheck and make sure the reload is needed
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
        if !item.isPlaybackLikelyToKeepUp {
            //you can create a new AVItem here 
            player?.replaceCurrentItem(with: item)
        }
        self.isPlaying ? self.playSong() : self.player?.pause()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM