Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check status of AVPlayer?

I thought that I could check the status of an AVPlayer simply by the property "rate".

This is how I create a player instance:

player = AVPlayer(URL: stream) // streaming from the internet
player!.play()

At some later point I would do something like this

println(player!.rate)

This is what I discovered:

  • In Simulator I get "0.0" in case the player is not running or "1.0" if it is running.
  • If I start the player but interrupt the internet connection it changes values from 1 to 0.
  • However, on my iPhone the property keeps value 1 even if I enter Airplane Mode?!

Do you have any idea why that happens and how I could check the stream condition otherwise?

I have tried an observer so far:

player!.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.New, context: nil)

But even the method "observeValueForKeyPath" does not get fired in my iPhone test case.

like image 223
andreas Avatar asked Nov 13 '14 01:11

andreas


People also ask

How to detect when AVPlayer video ends playing?

If you want to check the status of a played video - one of the best solutions is to add an observer to the AVPlayer item . The AVPlayerViewController doesn't notify about the ending of a video. This is why you need to check it by yourself. You should add the NotificationCenter observer to your playVideo() method.

How do I disable AVPlayer?

AVPlayer does not have a method named stop . You can pause or set rate to 0.0. Show activity on this post. I usually seekToTime 0.0, then pause.


2 Answers

Check out the Apple docs here and scroll to the "Key-Value Observing" section. Especially #3 in that section.

It helped me get my implementation to work. My resulting code looks like this:

//Global
var player = AVPlayer()

func setUpPlayer() {
    //...
    // Setting up your player code goes here
    self.player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
    //...
}

// catch changes to status
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("obsrved")
}
like image 82
Sean Avatar answered Oct 04 '22 10:10

Sean


I could not make it work with adding an observer on the currentItem as user @gabbler suggested.

However it helped using the notification center like this:

NSNotificationCenter.defaultCenter().addObserverForName(
    AVPlayerItemFailedToPlayToEndTimeNotification, 
    object: nil, 
    queue: nil, 
    usingBlock: { notification in
        self.stop()
    })

Note that stop() is a method in the same class which stops the stream as if a stop button were clicked.

like image 25
andreas Avatar answered Oct 04 '22 10:10

andreas