我正在开发用Swift
编写的音乐播放器应用程序,使用AVPlayer
的音频流,一切都很好
但是当我试图将mpremotecommandcenter添加到我的应用程序时,有很多错误我甚至不知道为什么会发生这种情况。
link to video that describes my problem
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()
}
最佳答案
除了您提供的代码之外,您还可以在应用程序委托中的某个位置调用以下内容:
UIApplication.shared.beginReceivingRemoteControlEvents()
除了使用
MPRemoteCommandCenter.shared()
之外,这样做似乎会导致种族状况。根据Apple's documentation:
在ios 7.1及更高版本中,使用共享的mpremotecommandcenter对象注册远程控制事件。使用共享命令中心对象时不需要调用此方法。
此方法使用响应程序链启动远程控制事件的传递。
从你的应用程序委托中删除该方法,你就应该没事了。
关于swift - MPRemoteCommandCenter播放/暂停触摸时闪烁,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53989356/