1

The following Swift 5 function is what I'm using to display local MP4 video with native controls and looping at default. I was wondering if anyone had a more efficient way of incorporating a new function (e.g. AVPlayerLooper) to achieve the same functionality?

import Foundation
import AVFoundation
import AVKit

class VideoPlayer
{
    public var VideoVC = AVPlayerViewController()
    
    func playVideo(fileName:String, inView:UIView)
    {
        if let path = Bundle.main.path(forResource: fileName, ofType: "mp4")
        {
            let videoURL = URL(fileURLWithPath: path)
            VideoVC.showsPlaybackControls = true
            VideoVC.player = AVPlayer(url: videoURL)
            inView.addSubview(VideoVC.view)
            VideoVC.view.frame = inView.bounds
            VideoVC.player?.isMuted = true
            VideoVC.player?.play()
            
            NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.VideoVC.player?.currentItem, queue: .main)
            { [weak self] _ in
                self?.VideoVC.player?.seek(to: CMTime.zero)
                self?.VideoVC.player?.play()
            }
        }
    }
}

Appreciate all insight in advance!

1 Answers1

0

Did you try to combine some of the answers here - Looping a video with AVFoundation AVPlayer??

import Foundation
import AVFoundation
import AVKit

class VideoPlayer
{
    public var VideoVC = AVPlayerViewController()
    private var playerLooper: AVPlayerLooper!
    
    func playVideo(fileName:String, inView:UIView)
    {
        if let path = Bundle.main.path(forResource: fileName, ofType: "mp4")
        {
            let videoURL = URL(fileURLWithPath: path)
            VideoVC.showsPlaybackControls = true
            --------------------------------------------------------
            let playerItem = AVPlayerItem(url: videoURL)
            VideoVC.player = AVQueuePlayer(playerItem: playerItem)
            playerLooper = AVPlayerLooper(player: player, templateItem: playerItem)
            --------------------------------------------------------
            inView.addSubview(VideoVC.view)
            VideoVC.view.frame = inView.bounds
            VideoVC.player?.isMuted = true
            VideoVC.player?.play()
            
            NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.VideoVC.player?.currentItem, queue: .main)
            { [weak self] _ in
                self?.VideoVC.player?.seek(to: CMTime.zero)
                self?.VideoVC.player?.play()
            }
        }
    }
}
CloudBalancing
  • 1,461
  • 2
  • 11
  • 22