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



我试图找到一种方法来观察播放器,这样我就可以检测到用户何时增加或减少Apple TV上的音量


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`
}

相关内容

  • 没有找到相关文章

最新更新