periodicTimeObserver 用于 AVPlayer 中的持续时间倒计时 Swift

periodicTimeObserver for duration countdown in AVPlayer with Swift

我有一个 AVPlayer 的时间观察器,效果很好。我试图让它从音频 0 的持续时间开始倒计时。

它工作正常,现在确实倒计时我只是在格式化方面遇到了一些问题。

如果你看到下面的图片,你就会明白我的意思了。它从整个 minutes:seconds 3:00,到奇怪的数字 3:-1 等等。

知道我做错了什么吗?

这里是定时器的代码:

let interval = CMTime(value: 1, timescale: 1)
self.audioPlayer?.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main, using: { (progressTime) in

let secondsProgress = CMTimeGetSeconds(progressTime)

    let secondsStringProgress = String(format: "%02d", Int((secondsProgress.truncatingRemainder(dividingBy: 60))))
    let minuitesStringProgress = String(format: "%02d", Int(secondsProgress) / 60)
    //self.countDownLabel.text = "\(minuitesStringProgress):\(secondsStringProgress)"

    if let duration = self.audioPlayer?.currentItem!.asset.duration {

        let secondsDuration = CMTimeGetSeconds(duration)

            let secondsStringDuration = String(format: "%02d", Int((secondsDuration.truncatingRemainder(dividingBy: 60))))
            let minuitesStringDuration = String(format: "%02d", Int(secondsDuration) / 60)

                let secondsString = String(format: "%02d", Int(secondsStringDuration)! - Int(secondsStringProgress)!)
                let minuitesString = String(format: "%02d", Int(minuitesStringDuration)! - Int(minuitesStringProgress)!)

            self.countDownLabel.isHidden = false
            self.countDownLabel.text = "\(minuitesString):\(secondsString)"

        self.horizontalSlider.value = Float(secondsProgress / secondsDuration)
        self.circleSlider.value = Float(secondsProgress / secondsDuration)

    }
})

我用这个函数来显示格式化日期

  func getFormatedTime(FromTime timeDuration:Int) -> String {

    let minutes = Int(timeDuration) / 60 % 60
    let seconds = Int(timeDuration) % 60
    let strDuration = String(format:"%02d:%02d", minutes, seconds)
    return strDuration
  }

这样使用

        let strDuration = self.getFormatedTime(FromTime: recordingDuration)

或者直接在addPeriodicTimeObserver方法中这样

      recordingDuration = Float(CMTimeGetSeconds((self.playerItem?.asset.duration)!))-Float(CMTimeGetSeconds((self.playerItem?.currentTime())!))

将其传递给 getFormatedTime 设置 return 值的文本

两行代码