Ios 使用MPMusicLayerApplicationController时如何更新MPNowPlayingFoCenter
我正在尝试用我正在播放的苹果音乐曲目的歌曲信息更新Ios 使用MPMusicLayerApplicationController时如何更新MPNowPlayingFoCenter,ios,swift,mpnowplayinginfocenter,Ios,Swift,Mpnowplayinginfocenter,我正在尝试用我正在播放的苹果音乐曲目的歌曲信息更新mpnowplayingfocenter。我已经做了以下工作: 将我的背景模式设置为:“音频、播放和画中画” 正确设置我的AVAudioSession类别: let session = AVAudioSession.sharedInstance() do { try session.setCategory(AVAudioSessionCategoryPlayback, with: []) try session.setActiv
mpnowplayingfocenter
。我已经做了以下工作:
将我的背景模式设置为:“音频、播放和画中画”
正确设置我的AVAudioSession
类别:
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback, with: [])
try session.setActive(true)
} catch let error as NSError {
print("Failed to set the audio session category and mode: \(error.localizedDescription)")
}
设置MPRemoteCommandCenter
以响应远程命令:
let commandCenter = MPRemoteCommandCenter.shared();
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget {event in
self.player.play()
return .success
}
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.addTarget {event in
self.player.pause()
return .success
}
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget {event in
self.goForward()
return .success
}
commandCenter.previousTrackCommand.isEnabled = true
commandCenter.previousTrackCommand.addTarget {event in
self.goBack()
return .success
}
并在开始和出现播放事件时使用正确信息更新mpnowplayingfocenter
:
let info: [String:Any] = [
MPMediaItemPropertyAlbumTitle : albumTitle,
MPNowPlayingInfoCollectionIdentifier : albumId,
MPMediaItemPropertyArtist : artistName,
MPNowPlayingInfoPropertyMediaType : mediaType,
MPMediaItemPropertyPersistentID : trackId,
MPMediaItemPropertyTitle : trackTitle,
MPMediaItemPropertyPlaybackDuration : trackDuration,
MPNowPlayingInfoPropertyExternalContentIdentifier : trackId,
MPNowPlayingInfoPropertyPlaybackRate : isPlaying ? 1.0 : 0.0,
MPNowPlayingInfoPropertyPlaybackProgress : 0.5,
MPMediaItemPropertyArtwork : MPMediaItemArtwork(boundsSize: CGSize(width: 100, height: 100), requestHandler: { (size: CGSize) -> UIImage in
return UIImage(named: "play")! // dummy purposes
})
]
let infoCenter = MPNowPlayingInfoCenter.default()
infoCenter.nowPlayingInfo = info
infoCenter.playbackState = isPlaying ? .playing : .paused
我还需要做什么才能让歌曲信息显示在Control Center和锁定屏幕上?结果表明,代码100%正确,但在11.3之前的iOS 11中是一个bug。随着本周11.3的正式发布,上面的代码现在可以像苹果公司预期的那样使用
MPMusicLayerApplicationController