iFunnyVlogger
iFunnyVlogger

Reputation: 477

How To Make Play/Pause Button on Apple TV Remote Play/Pause AVAudioPlayer

I am making a music app for tvOS which has a AVAudioPlayer. I was wondering how to make the Play/Pause Button on Apple TV remote Play/Pause the AVAudioPlayer? Here's my current code:

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


}

I've been looking arround trying to figure this out. I haven't worked with tvOS before, so this is new for me. Thanks so much for the help!

Upvotes: 0

Views: 982

Answers (1)

picciano
picciano

Reputation: 22711

These functions have been working for us. They add a gesture recognizer that listens for the play/pause button on the remote. You can add this to your 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()
    }
}

Upvotes: 1

Related Questions