I was wondering how I can make a AVAudioPlayer play/pause with the Apple TV remote. This is my ViewController file so far:
import UIKit
import AVFoundation
class MusicViewController: UIViewController, AVAudioPlayerDelegate {
@IBOutlet weak var progressView: UIProgressView!
// Create the AVAudioPlayer
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 AVAudioPlayer to play once the ViewController appears
override func viewDidAppear(_ animated: Bool) {
audioPlayer.play()
}
// Set the AVAudioPlayer to stop once the ViewController is dismissed
override func viewDidDisappear(_ animated: Bool) {
audioPlayer.stop()
}
func updateAudioProgressView()
{
if audioPlayer.isPlaying
{
// Update progress
progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: true)
}
}
}
I also added this line to 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) {
// Do something...
}
Now that you have all of that for reference, let me basically tell you what I need help with. I am making a tvOS app has a view controller and that view controller has an AVAudioPlayer. I want to have it to where the Apple TV remote's Play/Pause button plays and pauses the AVAudioPlayer. How do I do this? Thanks so much for the help!