gpt4 book ai didi

swift - 如何在 Apple TV 上制作播放/暂停按钮远程播放/暂停 AVAudioPlayer

转载 作者:行者123 更新时间:2023-11-28 15:43:27 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于swift - 如何在 Apple TV 上制作播放/暂停按钮远程播放/暂停 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43420193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com