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

问题描述:

我正在为具有AVAudioPlayer的tvOS制作音乐应用程序。我想知道如何在Apple TV远程播放/暂停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,所以这对我来说是新的。非常感谢你的帮助!

这些功能一直在为我们工作。他们添加一个手势识别器,用于监听遥控器上的播放/暂停按钮。您可以将其添加到您的应用程序委托。

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() 
    } 
} 
+0

好的!非常感谢!但是,如何将它关闭到audioPlayer.play()和audioPlayer.pause()动作之间关闭的位置? – iFunnyVlogger

+0

查看更新。你可能需要额外的逻辑,这取决于你在做什么,但这应该让你去。 – picciano

+0

非常感谢!唯一的问题是App Delegate不知道audioPlayer。 – iFunnyVlogger