检查AVPlayer的播放状态

122

有没有办法知道 AVPlayer 的播放是否停顿或已经结束?

13个回答

4
player.timeControlStatus == AVPlayer.TimeControlStatus.playing

2
这个答案可能是正确的,但是它需要解释才能更好地理解。仅有代码的答案并不被认为是“好”的答案。以下是一些关于如何撰写良好答案的指南:如何撰写一个好的答案?。来自审查 - MyNameIsCaleb

0
你可以像这样检查玩家是否使用计时器进行游戏:
let playerObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: DispatchQueue.main, using: { [weak self] time in
        if self?.player.timeControlStatus == .playing {
            debugPrint("#player - info: isPlaying")
            self?.playButton.isSelected = true
        } else if self?.player.timeControlStatus == .paused {
            debugPrint("#player - info: isPaused")
            self?.playButton.isSelected = false
        } else if self?.player.timeControlStatus == .waitingToPlayAtSpecifiedRate {
            debugPrint("#player - info: isWaiting") //Buffering
        }
    })

0
这是解决方案的AsyncStream版本。
extension AVPlayer {
    func isPlaying() -> AsyncStream<Bool> {
        AsyncStream { cont in
            let observation = self.observe(\.rate) { player, value in
                cont.yield(player.timeControlStatus == .playing)
            }
            cont.yield(timeControlStatus == .playing)
            cont.onTermination = { _ in
                observation.invalidate()
            }
        }
    }
}

然后你可以使用它
let stream = player.isPlaying()
for await isPlaying in stream {
    self.isPlaying = isPlaying
}

在SwiftUI中,你可以在.task中使用它。
.task {
    let stream = player.isPlaying()
    for await isPlaying in stream {
        self.isPlaying = isPlaying
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接