我有一个视频播放器,可以在iOS命令中心和锁定屏幕中播放。当我在应用程序中切换播放/暂停按钮时,它应该通过更新
例如,如果我使用自定义按钮暂停视频,在应用程序中,命令中心仍然显示暂停按钮(这意味着视频仍在播放,这是错误的)。
使用KVO,当播放器的
nowPlayingInfo
(MPNowPlayingInfoCenter
)来更新命令中心(MPRemoteCommandCenter
)中的播放/暂停按钮。我不确定为什么它没有更新。例如,如果我使用自定义按钮暂停视频,在应用程序中,命令中心仍然显示暂停按钮(这意味着视频仍在播放,这是错误的)。
这是我更新nowPlayingInfo
的方式:
func updateMPNowPlayingInforCenterMetadata() {
guard video != nil else {
nowPlayingInfoCenter.nowPlayingInfo = nil
return
}
var nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo ?? [String: Any]()
let image: UIImage
if let placeholderLocalURL = video.placeholderLocalURL, let placeholderImage = UIImage(contentsOfFile: placeholderLocalURL.path) {
image = placeholderImage
} else {
image = UIImage()
}
let artwork = MPMediaItemArtwork(boundsSize: image.size, requestHandler: { _ -> UIImage in
return image
})
nowPlayingInfo[MPMediaItemPropertyTitle] = video.title
nowPlayingInfo[MPMediaItemPropertyAlbumTitle] = video.creator?.name ?? " "
nowPlayingInfo[MPMediaItemPropertyArtwork] = artwork
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = Float(video.duration)
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = Float(currentTime) // CMTimeGetSeconds(player.currentItem!.currentTime())
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
nowPlayingInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = player.rate
nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
if player.rate == 0.0 {
state = .paused
} else {
state = .playing
}
}
使用KVO,当播放器的
rate
属性改变时,我调用这个函数:// MARK: - Key-Value Observing Method
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard context == &assetPlaybackManagerKVOContext else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
} else if keyPath == #keyPath(AVPlayer.rate) {
updateMPNowPlayingInforCenterMetadata()
}
}
有什么想法吗?
更新
虽然我找到了解决方案,但在我的情况下并不完美。所以在我的应用程序中,我有两个视图控制器。让我们称它们为FeedVC
和PlayerVC
。因此,FeedVC
具有始终播放但已静音的AVPlayer
。如果您单击其中一个,则会创建PlayerVC
并播放完整视频。如果我在进入PlayerVC
之前暂停FeedVC
中的AVPlayer
,则NowPlayingInfoCenter中的“播放/暂停”按钮将完美工作!
是否有一种方法可以使这项工作正常而无需暂停FeedVC
中的视频?
另一个问题是,如果我不暂停FeedVC
中的播放器,则经过时间
会继续计算。似乎如果多个播放器正在播放,则播放/暂停按钮和经过时间都不正确。