0Day Forums
Check play state of AVPlayer - Printable Version

+- 0Day Forums (https://0day.red)
+-- Forum: Coding (https://0day.red/Forum-Coding)
+--- Forum: Objective-C (https://0day.red/Forum-Objective-C)
+--- Thread: Check play state of AVPlayer (/Thread-Check-play-state-of-AVPlayer)

Pages: 1 2


RE: Check play state of AVPlayer - guaiasanoloax - 07-21-2023

In iOS10, there's a built in property for this now: *timeControlStatus*

For example, this function plays or pauses the avPlayer based on it's status and updates the play/pause button appropriately.

@IBAction func btnPlayPauseTap(_ sender: Any) {
if aPlayer.timeControlStatus == .playing {
aPlayer.pause()
btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
} else if aPlayer.timeControlStatus == .paused {
aPlayer.play()
btnPlay.setImage(UIImage(named: "control-pause"), for: .normal)
}
}

As for your second question, to know if the avPlayer reached the end, the easiest thing to do would be to set up a notification.

NotificationCenter.default.addObserver(self, selector: #selector(self.didPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)

When it gets to the end, for example, you can have it rewind to the beginning of the video and reset the Pause button to Play.

@objc func didPlayToEnd() {
aPlayer.seek(to: CMTimeMakeWithSeconds(0, 1))
btnPlay.setImage(UIImage(named: "control-play"), for: .normal)
}

These examples are useful if you're creating your own controls, but if you use a AVPlayerViewController, then the controls come built in.


RE: Check play state of AVPlayer - urn833 - 07-21-2023

> **Answer in Objective C**

if (player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
//player is playing
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusPaused) {
//player is pause
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) {
//player is waiting to play
}


RE: Check play state of AVPlayer - Mrspermatozoon393 - 07-21-2023

You can check if the player is playing with a timer like this :

let playerObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main, using: { [weak self] time in
if self?.player.timeControlStatus == .playing {
debugPrint("#player - info: isPlaying")
self?.playButton.isSelected = true
} else if self?.player.timeControlStatus == .paused {
debugPrint("#player - info: isPaused")
self?.playButton.isSelected = false
} else if self?.player.timeControlStatus == .waitingToPlayAtSpecifiedRate {
debugPrint("#player - info: isWaiting") //Buffering
}
})