如何判断 AVPlayer 已经播放了三秒 Swift

How to tell when AVPlayer has been played for three seconds Swift

我有一个应用程序包含在 UIImageViewUITableView 中自动播放的视频,当单元格可见时,我想要做的就是让应用程序知道什么时候视频已播放三秒。我写了这段代码。

    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")
        }
      }
   }
}

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

尝试在播放器开始播放后调用观看次数

func updateView() {

    /// Not here Because at this time player current item is not initiated yet
    /// if you use Breakpoints in viewCount code you will see it won't enter
    /// in if condition created
    self.viewcount() /// Comment this line
    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 is initiated with a item to play
        player?.play()
        /// Call current time here
        /// Now it will Enter in if Condition 
        /// Also try using else statement so you know Do control enter in if or in Else
        self.viewcount()
    }


func viewcount()
    {
        if let currentitem = player?.currentItem
        {
            ///Yes Player have a item whose time can be Detected
            if currentitem.currentTime() == CMTimeMake(3, 1)
            {
                print ("VIDEO PLAYED FOR THREE SECONDS")
            }
        }
        else
        {
            /// Check do Control reach here in case 1 When you are calling before player.play()
        }
    }

您正在搜索播放器的观察者,这里是您可以检查和跟踪 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 为零,这将导致错误,请参阅此 ,如果 .你不需要它就不要添加它:)

注意 2:您应该保留 observer,以便在一段时间后您可以将其删除,这样就不会对内存造成额外的负担

希望对您有所帮助