[英]One AVPlayer's AVPlayerItemDidPlayToEndTime action executed for all Currently playing videos
Problem: In collectionview cell which has player问题:在有播放器的 collectionview 单元格中
if I play two Video simultaneously and seek first Video to end then AVPlayerItemDidPlayToEndTime
fired for two times and both videos restarted如果我同时播放两个视频并寻找第一个视频结束然后
AVPlayerItemDidPlayToEndTime
被触发两次并且两个视频都重新启动
In collection view cell I have在集合视图单元格中,我有
override func awakeFromNib() {
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main, using: {[weak self] (notification) in
if self?.player != nil {
self?.player?.seek(to: kCMTimeZero)
self?.player?.play()
}
})
}
and one play button action which play the video.和一个播放视频的播放按钮动作。
In cell I have slider to seek.在单元格中,我有滑块要查找。
Any Help would be appreciated任何帮助,将不胜感激
Make sure that player
and player?.currentItem
are not equal to nil
when you're registering for notifications.注册通知时,请确保
player
和player?.currentItem
不等于nil
。 To me, it seems like one of them was nil and you're basically subscribing to all of the .AVPlayerItemDidPlayToEndTime
notifications (since object
is nil).对我来说,似乎其中一个是零,你基本上订阅了所有
.AVPlayerItemDidPlayToEndTime
通知(因为object
是零)。
To avoid that, subscribe to the notifications right after assigning AVAsset
to the player.为避免这种情况,请在将
AVAsset
分配给播放器后立即订阅通知。
Swift 5.1斯威夫特 5.1
Pass the item as your object:将项目作为您的对象传递:
// Stored property
let player = AVPlayer(url: videoUrl)
// When you are adding your video layer
let playerLayer = AVPlayerLayer(player: player)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
// add layer to view
Then when you get that notification, here's how you can get the currentItem
:然后,当您收到该通知时,您可以通过以下方式获取
currentItem
:
// Grab the item from the notification object and ensure its the same item as the current players item
if let item = notification.object as? AVPlayerItem,
let currentItem = player.currentItem,
item == currentItem {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
// remove player from view or do whatever you need to do here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.