在iOS 11中,当我锁定iPhone时,我的音乐应用程序将显示锁定屏幕控件。我能够看到当前播放的歌曲以及播放/暂停向前和向后跳过。但是,在升级到Xcode 10 / iOS 12时,我再也看不到锁屏控件仅显示日期和时间...
但是,如果我向上滑动并获得该小部件屏幕(您可以在其中打开飞行模式等),我可以看到正在播放的信息。
这就是我所拥有的
在后台模式下
我已将代码更新为以下内容:
打来了我的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")]
}
我在do try
上设置了断点,它不打印任何一种打印功能,并跳过了try
我的代码转换错误吗?
答案 0 :(得分:2)
不要忘记设置MPRemoteCommandCenter
:
import MediaPlayer
//Use an AVPlayer
var player: AVPlayer!
var playerItem: AVPlayerItem!
您可以在viewDidLoad
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, mode: .default, 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
}
}