添加动作到Apple TV遥控播放/暂停按钮

时间:2017-04-15 17:02:23

标签: swift avaudioplayer tvos

我的应用程序中有一个AVAudioPlayer,我正在添加一个功能,用户可以按遥控器上的播放/暂停按钮来播放/暂停AVAudioPlayer。我在我的App Delegate中有这段代码:

    func initializePlayButtonRecognition() {
        addPlayButtonRecognizer(#selector(AppDelegate.handlePlayButton(_:)))
    }

    func addPlayButtonRecognizer(_ selector: Selector) {
        let playButtonRecognizer = UITapGestureRecognizer(target: self, action:selector)
        playButtonRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue as Int)]
        self.window?.addGestureRecognizer(playButtonRecognizer)

    }

    func handlePlayButton(_ sender: AnyObject) {
        if audioPlayer.isPlaying {
            audioPlayer.pause() {
            } else {
                audioPlayer.play()
            }

    }

}

AVAudioPlayer的名称是audioPlayer。我在代码中说明了这一点,但App Delegate没有从PlayerViewController引用AVAudioPlayer。我该怎么做呢?

1 个答案:

答案 0 :(得分:0)

您的代码看起来是正确的。只是缺少一个细节可以解释为什么它不能按预期工作...在tvOS中,除了设置allowedPressTypes之外,还需要将allowedTouchTypes定义为间接:

playButtonRecognizer.allowedTouchTypes = [NSNumber(value: UITouchType.indirect.rawValue)]