How do you loop AVPlayer in Swift?

后端 未结 8 2016
后悔当初
后悔当初 2020-12-02 15:15

Simple question I can\'t seem to find an answer to for some reason.

How do you loop AVPlayer in Swift?

numberOfLoops = -1 only works for AVAudioPlayer

<
8条回答
  •  -上瘾入骨i
    2020-12-02 15:36

    I've managed to create a seamless video looping for OSX in swift 3. It should work on iOS and with little modification on swift 2 as well.

    var player : AVQueuePlayer!
    
    // Looping video initial call
    internal func selectVideoWithLoop(url : URL)
    {
        let asset = AVAsset(url: url)
        player.pause()
        let playerItem1 = AVPlayerItem(asset: asset)
        let playerItem2 = AVPlayerItem(asset: asset)
        player.removeAllItems()
        player.replaceCurrentItem(with: playerItem1)
        player.insert(playerItem2, after: playerItem1)
        player.actionAtItemEnd = AVPlayerActionAtItemEnd.advance
        player.play()
    
        let selector = #selector(ViewController.playerItemDidReachEnd(notification:))
        let name = NSNotification.Name.AVPlayerItemDidPlayToEndTime
        // removing old observer and adding it again for sequential calls. 
        // Might not be necessary, but I like to unregister old notifications.
        NotificationCenter.default.removeObserver(self, name: name, object: nil)
        NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil)
    }
    
    // Loop video with threadmill pattern
    // Called by NotificationCenter, don't call directly
    func playerItemDidReachEnd(notification: Notification)
    {
        let item = player.currentItem!
        player.remove(item)
        item.seek(to: kCMTimeZero)
        player.insert(item, after: nil)
    }
    

    When you want to change the video, just call selectVideoWithLoop with a different url again.

提交回复
热议问题