在iOS 11中,当我锁定iPhone时,我的音乐应用程序会显示锁定屏幕控件.我能够看到当前播放的歌曲和播放/暂停向前和向后跳过.但是在升级到
Xcode 10 / iOS 12时,我再也看不到锁定屏幕只控制日期和时间……
@H_301_25@解决方法
但是,如果我向上滑动并获得小部件屏幕(您可以在其中打开飞行模式等),我可以看到正在播放的信息.
这就是我所拥有的
在背景模式中
在我的viewDidLoad中调用
do { try AVAudioSession.sharedInstance().setCategory(.soloAmbient,mode: .default,options: .allowAirPlay) print("Playback OK") try AVAudioSession.sharedInstance().setActive(true) print("Session is Active") } catch { print(error) } UIApplication.shared.beginReceivingRemoteControlEvents() self.becomeFirstResponder()
我之前没有在最后一个工作版本中使用以下代码,但我添加了它,因为我发现了类似的帖子,建议我这样做
if let songInfo = self.mediaPlayer.nowPlayingItem { nowPlayingInfoCenter.nowPlayingInfo = [ MPMediaItemPropertyTitle: songInfo.title ?? "",MPMediaItemPropertyArtist: songInfo.artist ?? "",MPMediaItemPropertyArtwork : songInfo.artwork?.image(at: CGSize(width: 400,height: 400)) ?? #imageLiteral(resourceName: "emptyArtworkImage")] }
我把断点放在试试看它不打印任何打印功能并跳过试试
我的代码转换错了吗?
不要忘记设置MPRemoteCommandCenter:
import MediaPlayer //Use an AVPlayer var player: AVPlayer! var playerItem: AVPlayerItem!
您可以在viewDidLoad中设置AVPlayer
override func viewDidLoad() { super.viewDidLoad() let path = Bundle.main.path(forResource: "My Heart Will Go On",ofType:"mp3")! let url = URL(fileURLWithPath: path) playerItem = AVPlayerItem(url: url) player = AVPlayer(playerItem: playerItem) setupAudioSession() }
像这样设置音频会话:
func setupAudioSession() { do { try AVAudioSession.sharedInstance().setCategory(.soloAmbient,options: .allowAirPlay) try AVAudioSession.sharedInstance().setActive(true) } catch { print("Error setting the AVAudioSession:",error.localizedDescription) } }
播放音频文件
func play() { player.play() setupNowPlaying() setupRemoteCommandCenter() }
设置MPNowPlayingInfoCenter
(根据您的代码自定义):
func setupNowPlaying() { // Define Now Playing Info var nowPlayingInfo = [String : Any]() nowPlayingInfo[MPMediaItemPropertyTitle] = "My Song" nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = playerItem.currentTime().seconds nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = playerItem.asset.duration.seconds nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate // Set the Metadata MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo MPNowPlayingInfoCenter.default().playbackState = .playing }
func setupRemoteCommandCenter() { 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 } }