2017-04-14 3 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

ありがとう!唯一の問題は、App DelegateがaudioPlayerについて認識していないことです。 – iFunnyVlogger

関連する問題