AVPlayer的addPeriodicTimeObserverForInterval:queue:usingBlock:方法是用于添加一个周期性的时间观察器,它会在指定的时间间隔内反复调用指定的block。但是该方法并没有提供直接的停止方法。
要停止周期性的时间观察器,我们可以使用AVPlayer的removeTimeObserver:方法来实现。在调用addPeriodicTimeObserverForInterval:queue:usingBlock:方法时,会返回一个观察器的唯一标识符,我们可以将该标识符保存起来,在需要停止观察器时,调用removeTimeObserver:方法,并传入保存的标识符即可。
下面是一个示例代码,演示如何使用addPeriodicTimeObserverForInterval:queue:usingBlock:方法,并在需要停止时进行处理:
// 创建AVPlayer实例
let player = AVPlayer()
// 添加周期性的时间观察器,每秒调用一次
let timeObserver = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: .main) { time in
// 在这里处理周期性触发事件的逻辑
print("Current time:", time.seconds)
}
// 停止观察器的方法
func stopPeriodicTimeObserver() {
// 判断观察器是否存在
if let observer = timeObserver {
// 停止观察器
player.removeTimeObserver(observer)
}
}
在需要停止观察器的地方,调用stopPeriodicTimeObserver()方法即可停止周期性的时间观察器。