ios 如何检测AVPlayer是否真的在swift中开始播放

ubof19bj  于 2022-12-01  发布在  iOS
关注(0)|答案(8)|浏览(200)

你好,我已经把UISlider的最小值设置为0.00。然后我用这种方法设置它的最大值。

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

但我得到了这个异常

*** 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

我知道在prepareForPlay()之后到实际播放需要一段时间才能真正播放视频。那么我如何检测播放器何时真正开始播放视频呢?请帮助我。谢谢

guicsvcw

guicsvcw1#

从iOS 10开始,您可以观察AVPlayer的timeControlStatus属性。它可以是.playing
检查代码:

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
            }
        }
    }
}
9ceoxa92

9ceoxa922#

下面是我所做的,以实际上知道什么时候视频开始(而不是当它只准备开始)。

雨燕4

player = AVPlayer(url: URL(fileURLWithPath: path))
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "rate" {
        if player.rate > 0 {
            print("video started")
        }
    }
}
jdg4fx2g

jdg4fx2g3#

您可以像这样在AVPlayer的对象上添加观察者

player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil)

您可以使用AVPlayer检查状态更改,如下所示

func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutableRawPointer) {
    if keyPath == "status" {
        print(player.status)
    }
}
oipij1gg

oipij1gg4#

来自苹果的docsYou can observe an AVPlayerLayer object’s readyForDisplay property to be notified when the layer has user-visible content. In particular, you might insert the player layer into the layer tree only when there is something for the user to look at and then perform a transition from

0yycz8jy

0yycz8jy5#

您可以创建一个Combine发布程序并观察rate

NotificationCenter.default.publisher(for: AVPlayer.rateDidChangeNotification, object: player)

在SwiftUI中,您可以接收以下值:

.onReceive(ratePublisher) { _ in
    let isPlaying = player.rate != 0
}
icomxhvb

icomxhvb6#

声明AVPlayer全局

var streamPlayer = AVPlayer()

func playStreamAudio( for audioUrl:String)
    {
        guard streamPlayer.timeControlStatus != .playing else {
            streamPlayer.pause()
            return
        }
        let url = audioUrl //"http://192.168.71.11:7891/rec.wav"
        let playerItem = AVPlayerItem(url: URL(string:url)!)
        streamPlayer = AVPlayer(playerItem:playerItem)
        streamPlayer.rate = 1.0;
        streamPlayer.volume = 1.0
        streamPlayer.play()
    }
goqiplq2

goqiplq27#

超级简单的解决方案SWIFT 4-5:

只需检查timeControlStatus!:(也可与PlayerQueue配合使用)

if avPlayer?.timeControlStatus.rawValue == 2 {
       
    //video is playing (playing)

    } else if avPlayer?.timeControlStatus.rawValue == 0 { 
    
    //video is not playing (paused)
    
    }

原始值将提供其当前状态:)

x33g5p2x

x33g5p2x8#

另一种更简单的方法是:

if videoPlayer.rate != 0 && videoPlayer.error == nil {
            print("video player is playing.................")
        } else {
            print("video player is NOT playing.")
        }

其中videoPlayer的类型显然是AVPlayer。

相关问题