0
votes

I want to know that how i can check that AVPlayer is not playing music when i click on play Button(player.play()) and it currently (buffering or loading) due to slow internet connection or due to other causes, and also check when it play music after buffering. Because i need to add UIActivityIndicatorView on Play button. When Play button is clicked it animate till the buffering and when AVPlayer play song after buffering it stop animating and when it AVPlayer again start buffering it again animate. Can anyone please tell me how i can do this with simple way like this

if (player is buffering){
    activityIndicator.tartAnimating()
}else if player is playing music{
    activityIndicator.stopAnimating()
}

and also check again and again using NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "check", userInfo: nil, repeats: true)

Or any other simple solution? Thanks.

1

1 Answers

0
votes

This seems similar to a question I answered here: https://stackoverflow.com/a/42148482/5100819

The approach we used to update the UI when the AVPlayer finishes buffering and starts actual audible playback would likely do the job. We used a boundary time to execute a block at the start of playback – specifically after 1/3 of a second of playback – to update the UI at roughly the same time as audio is heard:

let times = [NSValue(time:CMTimeMake(1,3))]
_ = self.player.addBoundaryTimeObserver(forTimes: times, queue: DispatchQueue.main, using: {
    [weak self] time in
    // Code to update the UI goes here, e.g.
    activityIndicator.stopAnimating()
})

I have a little more detail on the approach (and a sample Xcode project) on our company blog: http://www.artermobilize.com/blog/2017/02/09/detect-when-ios-avplayer-finishes-buffering-using-swift/