使用 AVPlayer 时,如何检测用户何时取消 swift 中的视频静音

How do I detect when a user unmutes a video in swift when using AVPlayer

我正在尝试确定用户在观看视频时是否点击了取消静音按钮。我知道 player.isMuted 但我不确定如何检查值是否有变化。我正在使用 AVPlayerVideoViewController 并想覆盖取消静音按钮功能。

我创建了一个示例ViewController,您可以轻松观察isMuted变化:

import AVKit

class ViewController: AVPlayerViewController {
    var muteObservation: NSKeyValueObservation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let videoPath = Bundle.main.path(forResource: "video", ofType: "mov") else {
            return
        }

        let videoURL = URL(fileURLWithPath: videoPath)
        player = AVPlayer(url: videoURL)
        player?.play()
        
        muteObservation = player?.observe(\.isMuted) { player, _ in
            print("isMuted: \(player.isMuted)")
        }
    }
}