我使用AVPlayer播放简单的MP4视频。我需要知道视频何时结束,因此我为通知AVPlayerItemDidPlayToEndTime
添加了一个观察者。
如果视频在设备上播放,则效果很好,但如果我们通过AirPlay将视频从设备流传输到带有tvOS 12.2的Apple TV(第四代),则永远不会发布通知。
奇怪的是,此问题仅出现在MP4视频上,而没有出现在HLS流(m3u8)上,这使我想知道这是否可能是tvOS(或AirPlay)错误。
我创建了一个小的POC来隔离问题,这就是我要做的:
let bunny = "https://www.sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4"
// create a new player with every call to startVideo() for demo purposes
func startVideo() {
// remove layer of current play from playerContainer as
// a new one will be created below
if let sublayers = playerContainer.layer.sublayers {
for layer in sublayers {
layer.removeFromSuperlayer()
}
}
if let videoUrl = URL(string: bunny) {
// create player with sample video URL
self.player = AVPlayer(url: videoUrl)
guard let player = self.player else {return}
// add player layer to playerContainer
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = playerContainer.bounds
playerLayer.videoGravity = .resizeAspectFill
playerContainer.layer.addSublayer(playerLayer)
// add block-based observer to listen for AVPlayerItemDidPlayToEndTime event
let _ = NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: player.currentItem,
queue: .main) { notification in
print("Item did finish playing! \(notification)")
}
player.play()
}
}
再次澄清一下,如果以下条件之一为 true ,则这很好用:
我也尝试了以下操作,但结果是相同的:
currentItem
设置为对象。感谢您的帮助。这可能是this question的重复,但是由于没有答案,并且链接的问题是关于HLS而不是MP4的,因此我还是决定发布此问题。