gpt4 book ai didi

ios - 如何判断 AVPlayer 已播放三秒 Swift

转载 作者:行者123 更新时间:2023-11-30 11:37:08 25 4
gpt4 key购买 nike

我有一个应用程序,其中包含当单元格可见时在 UITableView 中的 UIImageView 中自动播放的视频,而我要做的就是允许该应用程序了解视频何时播放了三秒。我写了这段代码。

    class PostCell: UITableViewCell {

var player: AVPlayer?
var playerLayer: AVPlayerLayer?

var post: Post? {
didSet {
updateView()
}
}

func updateView() {

self.viewcount()

if let videoUrlString = post?.videoUrl, let videoUrl = URL(string: videoUrlString) {
player = AVPlayer(url: videoUrl)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = postImageView.frame
playerLayer?.frame.size.width = postImageView.frame.size.width
playerLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
self.contentView.layer.addSublayer(playerLayer!)

player?.play()
}
func viewcount() {
if let currentitem = player?.currentItem {
if currentitem.currentTime() == CMTimeMake(3, 1) {
print ("VIDEO PLAYED FOR THREE SECONDS")
}
}
}
}

但是一旦视频开始播放,它就不会打印出我的消息。我在网上搜索了帮助,但找不到有关此主题的任何内容。那么有人可以帮助解决我的问题并告诉我我做错了什么吗?

最佳答案

您正在寻找玩家的观察者,这里是您如何检查和跟踪 AVPlayer 的当前位置

这是向单元格添加观察者的函数

private func addObserversForVideoPlayer(cell:CustomCell) {

let observer = cell.player?.addPeriodicTimeObserver(forInterval: CMTime.init(seconds: 1, preferredTimescale: 1), queue: .main, using: {[weak self,weak cell] (time) in
guard let cell = cell else {return}

if cell.player?.currentItem?.status == .readyToPlay {
// print("Inside Will DISPLAY\(cell.video.currentTime)")

let timeDuration : Float64 = CMTimeGetSeconds((cell.player?.currentItem?.asset.duration)!)
cell.lblDuration.text = self?.getDurationFromTime(time: timeDuration)

let currentTime : Float64 = CMTimeGetSeconds((cell.player?.currentTime())!)
cell.lblStart.text = self?.getDurationFromTime(time: currentTime)
cell.slider.maximumValue = Float(timeDuration.rounded())
cell.slider.value = Float(currentTime.rounded())

}
})
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: cell.player?.currentItem, queue: .main, using: {[weak cell,weak self] (notification) in

if cell?.player != nil {
cell?.player?.seek(to: kCMTimeZero)
cell?.player?.play()
}
})
}

这样 addPeriodicTimeObserver 将在播放器开始播放时通知您。

并且 NSNotification.Name.AVPlayerItemDidPlayToEndTime 会在 AVPlayer 停止时通知您。

注意1:如果在添加 AVPlayerItemDidPlayToEndTime 时您的 cell.player?.currentItem 为零,则会导致错误,请参阅此 One AVPlayer's AVPlayerItemDidPlayToEndTime action executed for all Currently playing videos , 如果 。你不需要它就不要添加它:)

注意2:您应该保留observer,这样您就可以在一段时间后将其删除,这样就不会在内存上承受额外的负载

希望对你有帮助

关于ios - 如何判断 AVPlayer 已播放三秒 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49620882/

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