我正在开发用Swift编写的音乐播放器应用程序,使用AVPlayer的音频流,一切都很好
但是当我试图将MPRemoteCommandCenter添加到我的应用程序时,有很多bug我甚至不知道为什么会发生
AVPlayer实现如下:
func setupPlayer() {
let item = AVPlayerItem(url: musicURL)
self.player = AVPlayer.init(playerItem: item)
self.player.play()
self.player.volume = 1
self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main, using: { (time) in
if self.player.currentItem?.status == .readyToPlay {
self.reloadNowPlayingInfo()
let currentTime = self.player.currentTime().seconds
self.playingTime.text = currentTime.getTimeString()
self.playerSlider.value = currentTime/duration
}
})
}
func reloadNowPlayingInfo() {
var info = [String : Any]()
info[MPMediaItemPropertyTitle] = self.titleText
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork.init("some image")
info[MPMediaItemPropertyPlaybackDuration] = seconds
info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = currentSecs
info[MPMediaItemPropertyArtist] = "Artist name"
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
}对于指挥中心来说,
MPRemoteCommandCenter实现如下:
func setupCommandCenter() {
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.pauseCommand.isEnabled = true
commandCenter.playCommand.addTarget(self, action: #selector(self.playCommand(_:)))
commandCenter.pauseCommand.addTarget(self, action: #selector(self.pauseCommand(_:)))
}
@objc func playCenter(_ action: MPRemoteCommandEvent) {
self.state = .play
self.playBtn.setBackgroundImage("some image"), for: .normal)
self.player.play()
self.fetchTracks()
}
@objc func pauseCenter(_ action: MPRemoteCommandEvent) {
self.state = .pause
self.playBtn.setBackgroundImage("some image"), for: .normal)
self.player.pause()
self.fetchTracks()
}发布于 2019-01-18 10:09:37
除了您提供的代码之外,您还可以在应用程序委托的某个地方调用以下内容:
UIApplication.shared.beginReceivingRemoteControlEvents()除了使用MPRemoteCommandCenter.shared()之外,这样做似乎会导致一种竞争状况。
根据苹果的文档
在iOS 7.1及更高版本中,使用共享MPRemoteCommandCenter对象注册远程控制事件。在使用共享命令中心对象时,不需要调用此方法。 此方法使用响应链启动远程控制事件的传递。
从应用程序委托中删除该方法,您应该会没事的。
发布于 2019-05-29 19:28:06
如果在代码中添加2个观察者以接收播放机通知。您可能会在播放器锁定屏幕中看到滞后或跳跃。
避免添加观察者和一次目标。
commandCenter.playCommand.addTarget(self, action: #selector(self.playCommand(_:)))只有一次。当你不想要的时候把它拿掉
https://stackoverflow.com/questions/53989356
复制相似问题