使用KVO观察AVPlayer的timeControlStatus属性,以便检测播放状态的更改。
代码示例:
// 初始化AVPlayer
let player = AVPlayer(url: videoURL)
// 添加KVO观察者
player.addObserver(self, forKeyPath: "timeControlStatus", options: [.new, .old], context: nil)
// 实现KVO观察方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "timeControlStatus" {
guard let newStatusAsNumber = change?[.newKey] as? NSNumber, let oldStatusAsNumber = change?[.oldKey] as? NSNumber else {
return
}
let newStatus = AVPlayer.TimeControlStatus(rawValue: newStatusAsNumber.intValue)
let oldStatus = AVPlayer.TimeControlStatus(rawValue: oldStatusAsNumber.intValue)
if newStatus != oldStatus {
if newStatus == .playing {
// 当前正在播放
} else if newStatus == .paused {
// 当前已暂停
} else if newStatus == .waitingToPlayAtSpecifiedRate {
// 当前正在缓冲
}
}
}
}