【问题标题】:How to check status of AVPlayer?如何查看 AVPlayer 的状态?
【发布时间】:2014-11-13 01:59:56
【问题描述】:

我认为我可以通过属性“rate”来检查 AVPlayer 的状态。

这就是我创建播放器实例的方式:

player = AVPlayer(URL: stream) // streaming from the internet
player!.play()

稍后我会做这样的事情

println(player!.rate)

这是我发现的:

  • 在模拟器中,如果播放器未运行,我会得到“0.0”,如果正在运行,则会得到“1.0”。
  • 如果我启动播放器但中断互联网连接,它会将值从 1 更改为 0。
  • 但是,在我的 iPhone 上,即使我进入飞行模式,该属性也会保持值为 1?!

您知道为什么会发生这种情况以及我如何检查流条件吗?

到目前为止,我已经尝试过观察者:

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

但在我的 iPhone 测试用例中,即使是“observeValueForKeyPath”方法也没有被触发。

【问题讨论】:

  • 你可以尝试使用 player!.currentItem.addObserver 应该会被触发。
  • 哦,那会很尴尬...我明天去看看,谢谢!

标签: ios stream avplayer status rate


【解决方案1】:

查看the Apple docs here 并滚动到“Key-Value Observing”部分。 尤其是那个部分的#3

它帮助我实现了工作。我生成的代码如下所示:

//Global
var player = AVPlayer()

func setUpPlayer() {
    //...
    // Setting up your player code goes here
    self.player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions(), context: nil)
    //...
}

// catch changes to status
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("obsrved")
}

【讨论】:

  • 小改动override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { print("obsrved") }
【解决方案2】:

我无法按照用户 @gabbler 的建议在 currentItem 上添加观察者。

但是它有助于像这样使用通知中心:

NSNotificationCenter.defaultCenter().addObserverForName(
    AVPlayerItemFailedToPlayToEndTimeNotification, 
    object: nil, 
    queue: nil, 
    usingBlock: { notification in
        self.stop()
    })

请注意,stop() 是同一类中的一个方法,它会像单击停止按钮一样停止流。

【讨论】:

    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多