如何在Apple TV上播放/暂停按钮播放/暂停AVAudioPlayer

时间:2017-04-14 22:48:55

标签: swift avaudioplayer tvos

我正在为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合作过,所以这对我来说是新的。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

这些功能一直在为我们工作。他们添加了一个手势识别器,用于侦听遥控器上的播放/暂停按钮。您可以将此添加到您的应用代理。

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()
    }
}
相关问题