I have three urls and have to check if these urls have a video link to play or not. I have to esc link if it does not contain video in url and play video from next url. This following code will help to track the playing state.
let playerAV = AVPlayerViewController()
var player = AVPlayer()
playerAV.player = player
playerAV.view.frame = CGRectMake(0, 0, self.videoView.frame.width, self.videoView.frame.height)
self.addChildViewController(playerAV)
self.videoView.addSubview(playerAV.view)
playerAV.didMoveToParentViewController(self)
playerAV.player?.play()
addObserverOfMoviePlayer()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.notificationObserver(_:)), name:AVPlayerItemDidPlayToEndTimeNotification , object: player.currentItem)
_ = UIDevice.beginGeneratingDeviceOrientationNotifications
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ChannelDetailViewController.deviceOrientationDidChange(_:)) , name:
UIDeviceOrientationDidChangeNotification, object: nil)
playerAV.player!.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)
playerAV.player!.currentItem!.addObserver(self, forKeyPath: "playbackBufferEmpty", options: NSKeyValueObservingOptions.New, context: nil)
playerAV.player!.currentItem!.addObserver(self, forKeyPath: "playbackLikelyToKeepUp", options: NSKeyValueObservingOptions.New, context: nil)
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "rate" {
if let rate = change?[NSKeyValueChangeNewKey] as? Float {
if playerAV.player!.currentItem!.status == AVPlayerItemStatus.ReadyToPlay{
if rate != 0 && playerAV.player!.error == nil {
print("normal playback")
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ChannelDetailViewController.somAction), userInfo: nil, repeats: true)
}
else{
timer?.invalidate()
print("movie player stopped")
}
}else if playerAV.player!.currentItem?.status == AVPlayerItemStatus.Unknown{
timer?.invalidate()
print("not ready to play")
}
}
}
if keyPath == "playbackBufferEmpty"{
if playerAV.player?.currentItem?.playbackBufferEmpty == true{
timer?.invalidate()
print("movie player stopped due to no buffer")
}
}
if keyPath == "playbackLikelyToKeepUp" {
if playerAV.player?.currentItem?.playbackLikelyToKeepUp == true{
print("movie player playing after enough data in buffer")
playerAV.player?.play()
}
}
}
Just check the length of the video if it's invalid the length will return as zero with this code :
let assets = AVAsset(URL: NSURL(fileURLWithPath: filePath))
let length=Float(assets.duration.value)/Float(assets.duration.timescale)
if length != 0.0 {
// play it
}
If you have still problem you can ask me anytime.