iOS 12锁定屏幕控制音乐应用程序

前端之家收集整理的这篇文章主要介绍了iOS 12锁定屏幕控制音乐应用程序前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在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")]
}

我把断点放在试试看它不打印任何打印功能并跳过试试

我的代码转换错了吗?

解决方法

不要忘记设置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
}

MPRemoteCommandCenter

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
    }
}
原文链接:https://www.f2er.com/iOS/334053.html

猜你在找的iOS相关文章