gpt4 book ai didi

ios - 如何识别 AVPlayer 处于暂停状态并且用户正在清理

转载 作者:行者123 更新时间:2023-11-29 00:12:21 25 4
gpt4 key购买 nike

您好,我正在开发包含本地视频流的应用程序。当用户在暂停状态下擦洗时,我正在搜索回调或通知。我已经为 AVPlayer 添加了观察者,如下所示:

[self.avPlayerController.player addObserver:self forKeyPath:@"status" options:0 context:NULL];
[self.avPlayerController.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionOld context:NULL];

但是当播放器暂停和用户清理时不会调用观察者。我只想检测用户何时完成擦洗或何时触摸进度条。任何帮助将不胜感激。谢谢。

最佳答案

观察 ratestatus 应该有效——观察回调在我的代码中被调用,因此我假设它们也适用于你。我想问题是他们只有在视频暂停时才会被调用,而不是在用户删除视频时才会被调用。所以我会回答这个问题。

您可能想要观察的是currentTime。我自己尝试过,当我尝试观察 AVPlayer 或其 currentItem 时,都不会调用 KVO。我做了一些研究,看来这根本行不通(参见 this SO question )。你必须找到另一种方法来做到这一点。一种方法是添加一个计时器并定期检查它的状态。结合观察 ratetimeControlStatus ( see this answer ),即使视频暂停,您也应该能够判断用户正在更改 currentTime。

我希望你不介意阅读 Swift 代码,这是第一种方法:

class ViewController: UIViewController {

let player = AVPlayerViewController()
var timer: Timer? = nil
var previousTime: Double = 0
var stopped = false

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

present(player, animated: true, completion: {
self.player.player = AVPlayer(url: URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4")!)
self.player.player?.play()
self.player.player?.addObserver(self, forKeyPath: "rate", options: .new, context: nil)
self.timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (timer) in
let currentTime = self.player.player?.currentTime().seconds ?? 0
if self.previousTime != currentTime && self.stopped {
print(">>> User scrubbing")
}
self.previousTime = currentTime
})
})
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "rate" && (change?[NSKeyValueChangeKey.newKey] as? Float) == 0 {
print(">>> stopped")
stopped = true
} else if keyPath == "rate" && (change?[NSKeyValueChangeKey.newKey] as? Float) == 1 {
print(">>> played again")
stopped = false
}
}
}

第二种方法,我更喜欢的一种,是子类化 AVPlayer 并覆盖它的 seek(to:toleranceBefore:toleranceAfter:completionHandler:)方法。当用户滑动视频时,此方法由 AVPlayerViewController 调用 - 因此此时您可以知道用户正在滑动(尽管当用户在播放视频时滑动它时也会调用它,所以可能还需要测试它是否正在播放)。

class CustomAVPlayer: AVPlayer {
override func seek(to time: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime, completionHandler: @escaping (Bool) -> Void) {
super.seek(to: time, toleranceBefore: toleranceBefore, toleranceAfter: toleranceAfter, completionHandler: completionHandler)

// if you don't call this method directly, it's called only by the
// AVPlayerViewController's slider during scrubbing
print(">> user scrubbing")
}
}

关于ios - 如何识别 AVPlayer 处于暂停状态并且用户正在清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46109877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com