【问题标题】:How to update MPNowPlayingInfoCenter when using MPMusicPlayerApplicationController使用 MPMusicPlayerApplicationController 时如何更新 MPNowPlayingInfoCenter
【发布时间】:2018-03-25 20:19:44
【问题描述】:

我正在尝试使用我从 Apple Music 播放的曲目的歌曲信息更新 MPNowPlayingInfoCenter。我做了以下事情:

将我的背景模式设置为:“音频、Airplay 和画中画”,

正确设置我的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
}

并在开始时和每当有播放事件时使用正确的信息更新MPNowPlayingInfoCenter

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

我还需要做什么才能让歌曲信息显示在控制中心和锁定屏幕上?

【问题讨论】:

    标签: ios swift mpnowplayinginfocenter


    【解决方案1】:

    事实证明,代码 100% 正确,但在 iOS 11(11.3 之前)中是一个错误。随着本周 11.3 的正式发布,上面的代码现在可以像 Apple 预期的那样使用 MPMusicPlayerApplicationController

    【讨论】:

    • 您在使用 MPMusicPlayerApplicationController 时可以访问它吗?
    猜你喜欢
    • 2014-08-07
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2012-03-20
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多