Add Action To Apple TV Remote Play/Pause Button

我只是一个虾纸丫 提交于 2019-12-12 03:36:13

问题


I have an AVAudioPlayer in my app and I am adding a function where the user can press the Play/Pause button on the remote to Play/Pause the AVAudioPlayer. I have this code in my 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()
        }
    }
}

The AVAudioPlayer's name is an audio player. I have that stated in the code, but the App Delegate does not have a reference to the AVAudioPlayer from the PlayerViewController. How do I do this?


回答1:


Your code looks correct. Just a missing detail that could explain why it does not work as expected... in tvOS, apart from setting allowedPressTypes it is also needed to define allowedTouchTypes as indirect:

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


来源:https://stackoverflow.com/questions/43428807/add-action-to-apple-tv-remote-play-pause-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!