2017-04-14 21 views
0

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에서 일한 적이 없기 때문에 이것은 새로운 것이다. 도와 줘서 고마워!

답변

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

Ok! 정말 고마워! 그러나 audioPlayer.play() 및 audioPlayer.pause() 액션 사이를 전환하는 방법은 어떻게 얻을 수 있습니까? – iFunnyVlogger

+0

업데이트를 참조하십시오. 당신이하고있는 일에 따라 여기에 추가적인 논리가 필요할 수도 있지만, 이것은 당신을 끌어들일 것입니다. – picciano

+0

고마워요! 유일한 문제는 앱 위임자가 audioPlayer에 대해 알지 못한다는 것입니다. – iFunnyVlogger