Looping AVPlayer seamlessly

浪尽此生 提交于 2019-11-26 22:55:53

I had the same problem when streaming a video. After playing for the first time, there was a black screen when loading the video for second time. I got rid of the black screen by seeking video to 5ms ahead. It made nearly a seamless video loop. (Swift 2.1)

// Create player here..
let player = AVPlayer(URL: videoURL)

// Add notification block
NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: player.currentItem, queue: nil)
{ notification in
   let t1 = CMTimeMake(5, 100);
   player.seekToTime(t1)
   player.play()
}

If the video is very short (a few seconds), you can probably extract each frame as CGImage and use CAKeyframeAnimation to animate it. I am using this technique to play GIF images on my app and the animation is very smooth.

You mention that you looked at AVAnimator, but did you see my blog post on this specific subject of seamless looping? I specifically built seamless looping logic in because it could not be done properly with AVPlayer and the H.264 hardware.

I use two AVPlayerItems with the same AVAsset in an AVQueuePlayer and switch the items:

 weak var w = self
 NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil, queue: nil) { (notification) -> Void in
        let queuePlayer = w!.playerController.player! as! AVQueuePlayer
        if(queuePlayer.currentItem == playerItem1) {
            queuePlayer.insertItem(playerItem2, afterItem: nil)
            playerItem1.seekToTime(kCMTimeZero)
        } else {
            queuePlayer.insertItem(playerItem1, afterItem: nil)
            playerItem2.seekToTime(kCMTimeZero)
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!