1

I need to add a CABasicAnimation to an AVPlayerLayer when an AVQueuePlayer's playerItem is one second from finishing (playerItem's duration - 1). It's a basic crossfade. I just can't seem to figure out how to tell when I've arrived at the right time. Using the code below, I've added a periodic time observer. Is there any way to know when my playerItem is one second from ending?

timeObserverToken = player?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [unowned self] time in

    let fadeOutTime = CMTime(seconds: 1, preferredTimescale: time.timescale)
    let duration = self.currentItem()?.duration
    let convertedDuration = CMTimeConvertScale(duration!, time.timescale, .default)

    if CMTimeCompare(time, CMTimeSubtract(convertedDuration, fadeOutTime)) == 0 {
        self.playerLayer.add(self.fadeOut, forKey: "fadeOut")
    }
}
se_puede_dev
  • 585
  • 7
  • 16
  • 1
    You can use the BoundaryTimeObserver https://developer.apple.com/reference/avfoundation/avplayer/1388027-addboundarytimeobserver – Leo Dabus May 05 '17 at 01:28
  • http://stackoverflow.com/a/32082530/2303865 – Leo Dabus May 05 '17 at 01:29
  • That definitely helps! I have one video clip, taken from an iPhone, that, even with the BoundaryTimeObserver, it fades and then for a split second then reappears before the queuePlayer plays the next playerItem (when using the second commented `time` variable below). Using uncommented `time` variable it's better, but it stutters a little. Do I need to trim the clip? `let timeInterval: TimeInterval = seconds - 1.0` `// let time = NSValue(time: CMTimeMake(Int64(timeInterval), 1))` `let time = NSValue(time: CMTimeSubtract(item.duration, CMTimeMake(1, timeScale())))` – se_puede_dev May 05 '17 at 02:06

0 Answers0