【发布时间】:2021-09-26 08:45:22
【问题描述】:
今天我花了几个小时试图弄清楚为什么MPNowPlayingInfoCenter 不起作用,但没有成功。我希望它在控制中心和锁屏中显示信息,媒体是视频。
问题来了:
我有一个名为 GlobalAVPlayer 的单例类,它包含一个 AVPlayerViewController。它是一个单例,因为必须只有一个,而且我需要全局访问它。
class GlobalAVPlayer: NSObject {
static let sharedInstance = GlobalAVPlayer()
private var _currentVideo: Video?
var playerViewController = AVPlayerViewController()
var isPlaying: Bool = false
var almostPlaying: Bool = false
var hasItemToPlay: Bool = false
var currentVideo: Video?
{
set {
_currentVideo = newValue
notify_VideoChanged()
}
get {
return _currentVideo
}
}
private var player: AVPlayer!
override init()
{
super.init()
player = AVPlayer()
playerViewController.player = player
player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.New, context: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didPlayToEnd), name: "AVPlayerItemDidPlayToEndTimeNotification", object: nil)
}
func itemToPlay(item: AVPlayerItem)
{
if let player = player {
almostPlaying = true
hasItemToPlay = true
player.replaceCurrentItemWithPlayerItem(item)
}
}
func didPlayToEnd()
{
print("[GlobalAVPlayer] End video notification")
let time = CMTimeMakeWithSeconds(0, 1)
player.seekToTime(time)
}
func play()
{
if player.rate == 0
{
player.play()
if player.rate != 0 && player.error == nil
{
isPlaying = true
print("[GlobalAVPlayer] Playing video without errors")
}
}
}
func pause()
{
if player.rate == 1
{
player.pause()
if player.rate == 0 && player.error == nil
{
isPlaying = false
print("[GlobalAVPlayer] Pausing video without errors")
}
}
}
func notify_PlaybackChanged()
{
NSNotificationCenter.defaultCenter().postNotificationName("globalAVPlayerPlaybackChanged", object: self)
}
func notify_VideoChanged()
{
NSNotificationCenter.defaultCenter().postNotificationName("globalAVPlayerVideoChanged", object: self)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "rate" {
let newRate = change!["new"] as! Int
//rate = 0 (il player è fermo) rate = 1 (il player sta andando)
self.isPlaying = newRate == 1 ? true : false
notify_PlaybackChanged()
}
}
deinit
{
player.removeObserver(self, forKeyPath: "rate", context: nil)
}
}
应用程序启动时调用一次init,之后我使用“itemToPlay”方法更改视频。 我也正确(我认为)在 AppDelegate 中配置了音频会话:
do
{
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategoryPlayback)
try session.setActive(true)
}
catch
{
print("[AppDelegate] Something went wrong")
}
我尝试将MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = something 放在任何地方,但是当我将其放入play() 方法时,我最多可以在控制中心看到视频标题1 秒钟。之后它消失了,播放控件变灰了。信息已正确存储,因为当我将nowPlayingInfo 内容打印到控制台时,一切都按预期进行。
我尝试在不同的地方使用becomeFirstResponder 和UIApplication.beginReceivingRemoteControlEvents,但没有成功。
谢谢
【问题讨论】: