AVKit –视频片段仅循环播放2次

时间:2018-11-28 16:54:44

标签: ios swift avplayerviewcontroller avqueueplayer avkit

我有四个视频剪辑,我想不断地播放它们。但是我的AVQueuePlayer()仅将所有视频循环播放2次,然后停止播放。

如何让它们不断播放

这是我的代码:

import UIKit
import AVKit

class ViewController: UIViewController {

    private let player = AVQueuePlayer()
    let clips = ["001", "002", "003", "004"]
    private var token: NSKeyValueObservation?
    var avPlayerView = AVPlayerViewController()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addAllVideosToPlayer()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        self.addAllVideosToPlayer()
    }

    func addAllVideosToPlayer() {
        avPlayerView.player = player

        for clip in clips {
            let urlPath = Bundle.main.path(forResource: clip, ofType: "m4v")!
            let url = URL(fileURLWithPath: urlPath)
            let playerItem = AVPlayerItem(url: url)
            player.insert(playerItem, after: player.items().last)

            token = player.observe(\.currentItem) { [weak self] player, _ in
                if self!.player.items().count == 1 { self?.addAllVideosToPlayer() }
            }
            avPlayerView.showsPlaybackControls = false
            player.volume = 0.0
        }
        present(avPlayerView, animated: true, completion: { self.player.play() })
    }
}

1 个答案:

答案 0 :(得分:1)

我解决了我的问题。我删除了viewDidLoad()方法并将present()函数放入viewDidAppear()

这是它的样子:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)
    self.addAllVideosToPlayer()
    present(avPlayerView, animated: true, completion: { self.player.play() })
}