gpt4 book ai didi

ios - 如何使用 AVPlayerLooper 循环播放视频

转载 作者:IT王子 更新时间:2023-10-29 05:33:12 75 4
gpt4 key购买 nike

我尝试使用 AVPlayerLooper 在 TV OS 应用程序中循环播放视频,因为这应该可以消除再次播放视频时的暂停/打嗝。我观看了 WWDC2016 视频 https://developer.apple.com/videos/play/wwdc2016/503/并尝试实现代码,但它不会循环。我有一个 PlayerViewController 继承了 AVPlayerViewController。我放了代码让视频循环播放。如果我有以下代码,它什么也不显示。如果我将第二行更改为 self.queuePlayer = AVQueuePlayer(playerItem:playerItem),它只会播放一次。

  let playerItem = AVPlayerItem(url: url as URL)
self.queuePlayer = AVQueuePlayer() //I declared this as a variable in the view controller
self.playerLayer = AVPlayerLayer(player: self.queuePlayer) //I declared this as a variable in the view controller
let playerLooper = AVPlayerLooper(player: self.queuePlayer!, templateItem: playerItem)
self.view.layer.addSublayer(self.playerLayer!)
self.playerLayer?.frame = self.view.frame
self.queuePlayer?.play()

你们中有人成功地使用最新的 AVPlayerLooper 播放循环视频吗?

最佳答案

我自己解决了这个问题。

playerLooper 必须是类中的成员变量,否则它不起作用,因为局部变量在调用该方法后消失了。所以我把这一行放在类的开头来声明它。我没有将它声明为 AVPlayerLooper,因为这仅适用于 tvos10.0 和更新版本。我想让我的类(class)适配tvos9.0。这是我的工作代码。

var playerLooper: NSObject?
var playerLayer:AVPlayerLayer!
var queuePlayer: AVQueuePlayer?


func playVideo(_ filmName: String){
if let path = Bundle.main.path(forResource: filmName, ofType: "mov") {
let url = URL(fileURLWithPath: path)

if #available(tvOS 10.0, *) {

// Use a new player looper with the queue player and template item
let playerItem = AVPlayerItem(url: url as URL)
self.player = AVQueuePlayer(items: [playerItem])
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLooper = AVPlayerLooper(player: self.player! as! AVQueuePlayer, templateItem: playerItem)
self.view.layer.addSublayer(self.playerLayer!)
self.playerLayer?.frame = self.view.frame
self.player?.play()


} else {
// Fallback on earlier versions, this solution has hicup at end
player = AVPlayer(url: url)
player?.play()
loopVideo(player!)
}

}
}

func loopVideo(_ videoPlayer: AVPlayer) {
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) { notification in
if(!self.isStopped){

videoPlayer.seek(to: kCMTimeZero)
videoPlayer.play()

}
}
}

关于ios - 如何使用 AVPlayerLooper 循环播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258312/

75 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com