gpt4 book ai didi

ios - 使用remoteControlReceived控制音乐时遇到问题

转载 作者:行者123 更新时间:2023-11-30 12:20:25 25 4
gpt4 key购买 nike

我有 MusicPlayer View Controller ,您可以播放一些本地 mp3 文件。我需要为我的应用程序启用 remoteControlReceived 才能在应用程序外部更改音乐(播放/暂停、下一首)。我的问题是切换按钮仅在应用程序位于 MusicPlayerViewController 中时才起作用。例如,如果此 vc 关闭或转到后台,这些操作将不再起作用! 。首先,我在 MusicPlayerViewController 中设置这些通知:

  override func viewDidLoad() {
super.viewDidLoad()

//Control Music

NotificationCenter.default.addObserver(self, selector: #selector(playSong), name: NSNotification.Name("playSong"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(nextSong), name: NSNotification.Name("nextSong"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(previousSong), name: NSNotification.Name("previousSong"), object: nil)

}

然后在AppDelegate中:

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {


//Play music when it's on BG
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}

UIApplication.shared.beginReceivingRemoteControlEvents()

}



override func remoteControlReceived(with event: UIEvent?) {
if event!.type == UIEventType.remoteControl{
switch event!.subtype{
case UIEventSubtype.remoteControlPlay:
NotificationCenter.default.post(name: NSNotification.Name("playSong"), object: nil)

case UIEventSubtype.remoteControlPause:
NotificationCenter.default.post(name: NSNotification.Name("playSong"), object: nil)

case UIEventSubtype.remoteControlNextTrack:
NotificationCenter.default.post(name: NSNotification.Name("nextSong"), object: nil)

case UIEventSubtype.remoteControlPreviousTrack:
NotificationCenter.default.post(name: NSNotification.Name("previousSong"), object: nil)

default:
print("There is an issue with the control")
}
}
}

我无法从任何地方控制 AVPlayer 是什么问题!

PS: I also setup playing music in AppDelegate

最佳答案

您需要在AVAudioPlayer上应用类别。因此,您需要在分配 AVAudioPlayer 之后编写以下代码。

//分配你的音频播放器然后

do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}

UIApplication.shared.beginReceivingRemoteControlEvents()

希望这对您有帮助。

关于ios - 使用remoteControlReceived控制音乐时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44861629/

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