Reputation: 8411
Currently I have an AVPlayer controller that plays a specific video and loops it every time it reaches the end using
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(VideoPlayerController.playerItemDidReachEnd(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: self.player?.currentItem)
and
func playerItemDidReachEnd(notification: NSNotification) {
//code to restart player
}
I want to pause the player when it gets to a specific time in the video, for example one second before the end. How would I do this?
Is there a notification name like AVPlayerItemDidPlayToEndTimeNotification
that is used in this instance for detecting when a certain time is reached?
Upvotes: 0
Views: 910
Reputation: 5265
Use addPeriodicTimeObserverForInterval
to create a periodic event. In the event handler you can check the current time of the video, and pause if the time matches some criteria.
Example:
var player: AVPlayer!
var playerObserver: AnyObject!
func playVideo() {
self.addPlayerPeriodicObserver()
player.play()
}
func stopVideo() {
removePlayerPeriodicObserver()
player.pause()
}
func addPlayerPeriodicObserver() {
removePlayerPeriodicObserver()
// Time interval to check video playback.
let interval = CMTime(seconds: 0.01, preferredTimescale: 1000)
// Time limit to play up until.
let duration = player.currentItem!.duration
let limit = CMTime(seconds: 1.0, preferredTimescale: 1000)
let maxTime = duration - limit
// Schedule the event observer.
playerObserver = player?.addPeriodicTimeObserverForInterval(interval, queue: dispatch_get_main_queue()) { [unowned self] time in
if self.player.currentTime() >= maxTime {
// Time is at or past time limits - stop the video.
self.stopVideo()
}
}
}
func removePlayerPeriodicObserver() {
if let playerObserver = playerObserver {
player?.removeTimeObserver(playerObserver)
}
playerObserver = nil
}
Upvotes: 2
Reputation: 535284
You're looking for AVPlayer's addBoundaryTimeObserverForTimes:queue:usingBlock:
.
Upvotes: 2