Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when AvPlayer is stopped

Tags:

ios

avplayer

I'm using the AVPlayer class to read streams. I have to monitor playback.

Here is my question : Is it possible to detect when the player is stopped by the user ?

I looked at MPMoviePlayerController. If the user stopped the video, this controller sends a notification : MPMovieFinishReasonUserExited. Is there an equivalent ?

like image 395
tcacciatore Avatar asked Mar 18 '15 09:03

tcacciatore


2 Answers

here's the swift 3 code for @Thlbaut's answer

self.avPlayer?.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)

then

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "rate" {
        if let playRate = self.avPlayer?.rate {
            if playRate == 0.0 {
                print("playback paused")
            } else {
                print("playback started")
            }
        }
    }
}
like image 29
Rezwan Avatar answered Nov 15 '22 05:11

Rezwan


You can monitor rate property by adding observer on the player for key rate.

A value of 0.0 means pauses the video, while a value of 1.0 play at the natural rate of the current item.

Apple documentation and this topic.

Hope this helps.

like image 123
Thlbaut Avatar answered Nov 15 '22 03:11

Thlbaut