如何检测 tvOS 遥控器上的音量按钮按下

How to detect volume button press on tvOS remote

我试图找到一种观察播放器的方法,以便我可以检测到用户何时提高或降低 Apple TV 的音量。我已经设法通过使用以下方式使它适用于 iOS:


 var audioSession: AVAudioSession?

 audioSession?.addObserver(self, forKeyPath: "outputVolume", options: [.new], context: &videoPlayerViewControllerKVOContext)


 if keyPath == "outputVolume" {
        guard let mute = (change?[NSKeyValueChangeKey.newKey] as? NSNumber)?.floatValue else {
            return
        }
        
        var isMuted = false
        
        if (mute == 0) && (!player.isMuted) {
            isMuted = true
        } else if (mute.isZero) && (player.isMuted) {
            isMuted = false
        }
        
    }

但这不适用于 tvOS。有没有办法在 tvOS 上执行此操作?

不清楚所有其他代码,但您必须保留对创建的观察者的引用。

这是可能的解决方案(使用 Xcode 12.1 测试)

private var observer: NSKeyValueObservation?

// ... other code

self.observer = audioSession?.observe(\.outputVolume) { [weak self] (audioSession, _) in
    guard let `self` = self else { return }
    let mute = audioSession.outputVolume
    
    var isMuted = false
    if (mute == 0) && (!self.player.isMuted) {
        isMuted = true
    } else if (mute.isZero) && (self.player.isMuted) {
        isMuted = false
    }
    
    // do what's needed here with `isMuted`
}