Loop MP4 With AVPlayerLooper In UIView

This is the code I use to loop local MP4 files in a UIView element using AVPlayerLooper in Swift 5.

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: "mp4")
        {
            let url = URL(fileURLWithPath: path)


            let playerItem = AVPlayerItem(url: url as URL)
            _ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: .default, options: .mixWithOthers)
            videoPlayer = AVQueuePlayer(items: [playerItem])
            videoPlayer?.isMuted = true
            videoPlayer?.preventsDisplaySleepDuringVideoPlayback = false
            playerLooper = AVPlayerLooper(player: videoPlayer!, templateItem: playerItem)
            videoPlayerLayer = AVPlayerLayer(player: videoPlayer)
            videoPlayerLayer!.frame = inView.bounds

            inView.layer.addSublayer(videoPlayerLayer!)

            videoPlayer?.play()
        }
    }
    
    func remove()
    {
        videoPlayerLayer?.removeFromSuperlayer()
    }
}

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles