AVPlayerLooper没有循环播放本地视频

时间:2018-12-03 01:43:12

标签: ios swift macos avfoundation avkit

我正在尝试在我的macOS项目中播放视频,并且希望它不断循环播放。我能够让它播放一次,但是我不知道如何让它循环播放。我正在使用AVPlayerLooper,但似乎在某个地方弄乱了。这是我的代码:

import Cocoa
import AVKit
import AVFoundation

class ViewController: NSViewController {

    @IBOutlet weak var videoPlayer: AVPlayerView!

    override func viewDidLoad() {
        //var loop: AVPlayerLooper?

        super.viewDidLoad()

        guard let path = Bundle.main.path(forResource: "Background", ofType:"mp4") else {
            debugPrint("Not found")
            return
        }

        let asset = AVAsset(url: URL(fileURLWithPath: path))
        let item = AVPlayerItem(asset: asset)
        let queuePlayer = AVQueuePlayer(playerItem: item)
        let loop = AVPlayerLooper(player: queuePlayer, templateItem: item)
        videoPlayer.player = queuePlayer
        videoPlayer.player?.play()
    }
}

我的情节提要中也有一个AVPlayerView,它已连接到ViewController。

它可以构建并运行良好,但是当我运行它时,没有任何显示。我只是黑屏。

感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

  • AVPlayerLoop is sort of a "top level" object that manages both the player and the player item. So you have to keep it around, e.g. in a custom property of the view controller, or it will be released before it can really do anything

  • Since AVPlayerLoop manages the items in the AVQueuePlayer, initialize the queue player without passing in the player item