Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayerLooper doesn't loop through multiple videos

I created a AVPlayerView for non-stop playback of 4 videos using AVPlayerLooper. The problem is: AVPlayerView shows only one looped video. But I need to play a sequence (4 videos).

How to make AVPlayerLooper play all 4 videos and loop after that?

import Cocoa
import AVFoundation

class ViewController: NSViewController {

    @IBOutlet weak var viewOne: AVPlayerView!
    var playerLooper: AVPlayerLooper? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let videos = (1...4).map { _ in
            Bundle.main.urls(forResourcesWithExtension: "mov", 
                                          subdirectory: nil)![Int(arc4random_uniform(UInt32(4)))]
        }
    
        viewOne.player = AVQueuePlayer(url: videos[Int(arc4random_uniform(UInt32(4)))])
        let item = AVPlayerItem(url: videos[Int(arc4random_uniform(UInt32(4)))])
        playerLooper = AVPlayerLooper(player: viewOne.player as! AVQueuePlayer, templateItem: item)
        viewOne.player?.actionAtItemEnd = .advance
        viewOne.controlsStyle = .none

        NotificationCenter.default.addObserver(self, 
                                     selector: #selector(loopSequence), 
                                         name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, 
                                       object: viewOne.player?.currentItem)
    
        func loopSequence() {
            self.viewOne.player?.pause()
            self.viewOne.player?.currentItem?.seek(to: kCMTimeZero, completionHandler: nil)
            self.viewOne.player?.play()
        }
        loopSequence()
    }
}
like image 600
Andy Jazz Avatar asked Mar 07 '18 09:03

Andy Jazz


1 Answers

After finding the solution that had been previously answered and posting it in the comments, @andy asked me to post it as a solution. HERE is the previous answer by Harish that solved his problem.

like image 89
Jake Avatar answered Oct 17 '22 01:10

Jake