Я делаю музыкальное приложение для 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, поэтому для меня это ново. Большое спасибо за помощь!