要实现“播放视频时不显示MPNowPlayingInfoCenter,播放音频时显示”的效果,可以通过监听音频和视频的播放状态来动态设置MPNowPlayingInfoCenter的显示与隐藏。
首先,需要导入MediaPlayer框架。
import MediaPlayer
然后,创建一个播放器对象,例如AVPlayer。在播放音频时,设置MPNowPlayingInfoCenter的显示,而在播放视频时,设置MPNowPlayingInfoCenter的隐藏。
// 创建播放器对象
let player = AVPlayer()
// 监听播放状态
player.addObserver(self, forKeyPath: "status", options: .new, context: nil)
// 播放音频时显示MPNowPlayingInfoCenter
func playAudio() {
// 设置MPNowPlayingInfoCenter的显示信息
let infoCenter = MPNowPlayingInfoCenter.default()
infoCenter.nowPlayingInfo = [MPMediaItemPropertyTitle: "音频标题"]
// 开始播放音频
player.play()
}
// 播放视频时隐藏MPNowPlayingInfoCenter
func playVideo() {
// 隐藏MPNowPlayingInfoCenter
let infoCenter = MPNowPlayingInfoCenter.default()
infoCenter.nowPlayingInfo = nil
// 开始播放视频
player.play()
}
// 监听播放状态变化
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "status" {
if player.status == .readyToPlay {
if player.currentItem?.asset is AVURLAsset {
// 音频播放
playAudio()
} else {
// 视频播放
playVideo()
}
}
}
}
以上代码中,我们创建了一个AVPlayer对象,并通过KVO监听了其status属性的变化。当status变为.readyToPlay时,根据当前播放的媒体类型(音频或视频)来动态设置MPNowPlayingInfoCenter的显示与隐藏。
需要注意的是,在播放音频时,需要设置MPNowPlayingInfoCenter的显示信息,可以根据实际需求来设置标题、艺术家等信息。
另外,记得在不需要时移除观察者。
player.removeObserver(self, forKeyPath: "status")