xcode 在 iOS AVPlayer 中,似乎缺少 addPeriodicTimeObserverForInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40472326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:33:50  来源:igfitidea点击:

In iOS AVPlayer, addPeriodicTimeObserverForInterval seems to be missing

iosswiftxcodeavplayer

提问by S'rCat

I'm trying to setup AVPlayer.addPeriodicTimeObserverForInterval(). Has anyone used this successfully?

我正在尝试设置AVPlayer.addPeriodicTimeObserverForInterval(). 有没有人成功使用过这个?

I'm using Xcode 8.1, Swift 3

我使用的是 Xcode 8.1、Swift 3

采纳答案by Rajat

Check this func addPeriodicTimeObserver(forInterval interval: CMTime, queue: DispatchQueue?, using block: @escaping (CMTime) -> Void) -> Any

检查这个func addPeriodicTimeObserver(forInterval interval: CMTime, queue: DispatchQueue?, using block: @escaping (CMTime) -> Void) -> Any

It is in the documents also for example check this code snippet

它也在文档中,例如检查此代码片段

let timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [unowned self] time in 
}

Referenced from here

这里引用

回答by Yuchen Zhong

The accepted answer makes it feel like that you can assign the return value to a local variable and ignore it. But according to the doc, it is actually important the hold on strong reference to the return value and removeTimeObserver(_ :).

接受的答案让人感觉您可以将返回值分配给局部变量并忽略它。但根据doc,保持对返回值和的强引用实际上很重要removeTimeObserver(_ :)

You must maintain a strong reference the returned value as long as you want the time observer to be invoked by the player. Each invocation of this method should be paired with a corresponding call to removeTimeObserver(:) . Releasing the observer object without invoking removeTimeObserver(:) will result in undefined behaviour.

只要您希望玩家调用时间观察器,就必须维护返回值的强引用。此方法的每次调用都应与对 removeTimeObserver( :)的相应调用配对在不调用 removeTimeObserver(:) 的情况下释放观察者对象将导致未定义的行为。

So I would do:

所以我会这样做:

if let ob = self.observer {
    player.removeTimeObserver(ob)
}

let interval = CMTimeMake(1, 4) // 0.25 (1/4) seconds
self.observer = player.addPeriodicTimeObserver(forInterval: interval, queue: DispatchQueue.main) { [weak self] time in
    ...
}