【发布时间】:2018-12-31 16:09:36
【问题描述】:
我正在开发用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()
}
【问题讨论】:
-
您找到解决方案了吗?我刚刚遇到了同样的问题...
-
@mohamad 你找到解决方案了吗?我有同样的问题。
-
@RP-3 no same...,您的回答曾经很有帮助,但是当我再次尝试并删除
beginReceivingRemoteControlEvents时,锁定屏幕中的播放器完全消失了。 -
@Vipulk617 no.. 我在像 spotify 这样的好应用程序中也看到了这一点..
标签: swift avplayer mpremotecommandcenter