How to loop video with AVPlayerLooper

后端 未结 3 2358
一个人的身影
一个人的身影 2020-12-15 22:57

I try to loop a video in a TV OS app with the AVPlayerLooper because this should get rid of the pause/hicup when playing the video again. I watched the WW

3条回答
  •  爱一瞬间的悲伤
    2020-12-15 23:14

    Swift 5 custom class for playing a video looped without any glitches

    import Foundation
    import AVKit
    
    class VideoPlayerLooped {
    
        public var videoPlayer:AVQueuePlayer?
        public var videoPlayerLayer:AVPlayerLayer?
        var playerLooper: NSObject?
        var queuePlayer: AVQueuePlayer?
    
        func playVideo(fileName:String, inView:UIView){
    
            if let path = Bundle.main.path(forResource: fileName, ofType: "mov") {
    
                let url = URL(fileURLWithPath: path)
                let playerItem = AVPlayerItem(url: url as URL)
    
                videoPlayer = AVQueuePlayer(items: [playerItem])
                playerLooper = AVPlayerLooper(player: videoPlayer!, templateItem: playerItem)
    
                videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
                videoPlayerLayer!.frame = inView.bounds
                videoPlayerLayer!.videoGravity = AVLayerVideoGravity.resizeAspectFill
    
                inView.layer.addSublayer(videoPlayerLayer!)
    
                videoPlayer?.play()
            }
        }
    
        func remove() {
            videoPlayerLayer?.removeFromSuperlayer()
    
        }
    }
    

    Usage:

    let videoHolder = UIView()
    videoHolder.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
    
    var myVideoPlayerLooped = VideoPlayerLooped()
    videoPlayerLooped.playVideo(video: "myLocalMovFile", inView: videoHolder)
    

提交回复
热议问题