我正在尝试从远程命令中心接收关于何时点击播放/暂停按钮的通知,以便我可以适当地更新播放/暂停按钮的图像。但是,我没有收到有关何时按下播放命令/暂停命令的通知(即何时应该打印“轻按播放”或“轻按暂停”)。这是我第一次使用这个库,所以我跟着 Apples 文档,它说要使用 applicationMusicPlayer 或 applicationQueuePlayer 来实现一个音乐控制器来接收这些事件,但到目前为止我还不能。我不知道除了将其设置为 applicationQueuePlayer 之外是否还有其他需要做的事情。
这是我的代码,用于产生这种情况的非常简单的音乐播放器控制器:
let musicPlayer = MPMusicPlayerController.applicationQueuePlayer
override func viewDidLoad() {
super.viewDidLoad()
setupRemoteControl()
musicPlayer.setQueue(with: .songs())
}
func setupRemoteControl() {
UIApplication.shared.beginReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget { (_) -> MPRemoteCommandHandlerStatus in
print("tapped play")
return .success
}
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.addTarget {(_) -> MPRemoteCommandHandlerStatus in
print("tapped pause")
return .success
}
@IBAction func selectSongs(_ sender: UIButton) {
let controller = MPMediaPickerController(mediaTypes: .music)
controller.allowsPickingMultipleItems = true
controller.popoverPresentationController?.sourceView = sender
controller.delegate = self
present(controller, animated: true, completion: nil)
}
func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) {
musicPlayer.setQueue(with: mediaItemCollection)
mediaPicker.dismiss(animated: true, completion: nil)
musicPlayer.play()
}