Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
957 views
in Technique[技术] by (71.8m points)

ios - How to detect AVPlayer actually started to play in swift

Hello I have set my UISliderminimum value to 0.00. Then I set it's max value in this way.

self.viewPlayer.layer.addSublayer(playerLayer)
    let duration : CMTime = avPlayer.avPlayer.currentItem!.asset.duration
    let seconds : Float64 = CMTimeGetSeconds(duration)

    sliderBar.maximumValue=Float(seconds)
    sliderBar!.isContinuous = false
    sliderBar!.tintColor = UIColor.green

But I am getting this exception

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Attempting to set a slider's minimumValue (0.000000) to be larger than the maximumValue (nan)'
enter code here

I know after prepareForPlay() to actual playing it takes some time to really play the video. So how can I detect when the player really started to play the video? Please help me. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since iOS 10 you can observe timeControlStatus property of AVPlayer. It can be .playing.

Check the code:

private func setupAVPlayer() {
    avPlayer.addObserver(self, forKeyPath: "status", options: [.old, .new], context: nil)
    if #available(iOS 10.0, *) {
        avPlayer.addObserver(self, forKeyPath: "timeControlStatus", options: [.old, .new], context: nil)
    } else {
        avPlayer.addObserver(self, forKeyPath: "rate", options: [.old, .new], context: nil)
    }
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if object as AnyObject? === avPlayer {
        if keyPath == "status" {
            if avPlayer.status == .readyToPlay {
                avPlayer.play()
            }
        } else if keyPath == "timeControlStatus" {
            if #available(iOS 10.0, *) {
                if avPlayer.timeControlStatus == .playing {
                    videoCell?.muteButton.isHidden = false
                } else {
                    videoCell?.muteButton.isHidden = true
                }
            }
        } else if keyPath == "rate" {
            if avPlayer.rate > 0 {
                videoCell?.muteButton.isHidden = false
            } else {
                videoCell?.muteButton.isHidden = true
            }
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...