Search code examples
iosswiftavplayeravkitavqueueplayer

How to loop videos with AVQueuePlayer after it completes


I have an array of URLs that I then turn into an array of AVPlayerItems and use AVQueuePlayer to loop through the videos- usually 1-7 videos at a time. However when it stops I am not sure how to start it again to play the same array of videos until the user switches to a different view controller.


in viewDidLoad this creates the array of playerItems 
    //creates playerItems to play videos in a queue
       postURLs?.forEach{(url) in
           let asset = AVAsset(url: url)
           let playerItem = AVPlayerItem(asset: asset)
           playerItems.append(playerItem)  
       }


   public func playVideo() {
           player = AVQueuePlayer(items: playerItems)
           player.seek(to: CMTime.init(value: 0, timescale: 1))
           playerLayer = AVPlayerLayer(player:player)
           playerLayer.frame = self.lifieView.frame
           lifieView.layer.addSublayer(playerLayer)
           player.play()
           //restart video maybe? Tested but did not work - hits function 
           NotificationCenter.default.addObserver(
               forName: .AVPlayerItemDidPlayToEndTime,
               object: nil,
               queue: nil) { [weak self] _ in self?.restart2() }
       
   }

//this is test function to restart (works with AVPlayer with single video)
private func restart2(){
    player.seek(to: CMTime.zero)
    player.play()
   }

Solution

  • I got it working after much research and testing. What I did was change the restart function to first remove all items from the player, then go through the array of playerItems and add them back into the queue- then have the player start back at the beginning.

    func restartPlayer(){
            player.removeAllItems()
            playerItems.forEach{
                player.insert($0, after:nil)
            }
            player.seek(to: .zero)
            
        }