Как сделать кнопку воспроизведения/паузы на Apple TV Remote Play/Pause AVAudioPlayer

Я делаю музыкальное приложение для tvOS с AVAudioPlayer. Мне было интересно, как заставить кнопку «Воспроизведение / пауза» на пульте Apple TV воспроизводить / приостанавливать воспроизведение AVAudioPlayer? Вот мой текущий код:

import UIKit
import AVFoundation


class MusicViewController: UIViewController, AVAudioPlayerDelegate {

    @IBOutlet weak var progressView: UIProgressView!


    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()




        do {

            audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "Roots", ofType: "mp3")!))

            audioPlayer.prepareToPlay()

            var audioSession = AVAudioSession.sharedInstance()

            Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(updateAudioProgressView), userInfo: nil, repeats: true)
            progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: false)


            do {

                try audioSession.setCategory(AVAudioSessionCategoryPlayback)

            }

        }

        catch {

            print(error)

        }

        audioPlayer.delegate = self

    }


    //  Set the music to automaticly play and stop

    override func viewDidAppear(_ animated: Bool) {
        audioPlayer.play()


    }

    override func viewDidDisappear(_ animated: Bool) {
        audioPlayer.stop()

    }

    func updateAudioProgressView()
    {
        if audioPlayer.isPlaying
        {
   // Update progress
            progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: true)
        }
    }


}

Я искал вокруг, пытаясь понять это. Раньше я не работал с tvOS, поэтому для меня это ново. Большое спасибо за помощь!


person iFunnyVlogger    schedule 14.04.2017    source источник


Ответы (1)


Эти функции у нас работают. Они добавляют распознаватель жестов, который прослушивает кнопку воспроизведения/паузы на пульте дистанционного управления. Вы можете добавить это в свой делегат приложения.

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()
    }
}
person picciano    schedule 14.04.2017
comment
В порядке! Огромное спасибо! Но как мне сделать так, чтобы он отключался между действиями audioPlayer.play() и audioPlayer.pause()? - person iFunnyVlogger; 15.04.2017
comment
Смотрите обновление. Здесь вам может понадобиться дополнительная логика, в зависимости от того, что вы делаете, но это должно вам помочь. - person picciano; 15.04.2017
comment
Большое спасибо! Единственная проблема заключается в том, что App Delegate не знает о audioPlayer. - person iFunnyVlogger; 15.04.2017