Search code examples
swiftavplayeravplayerviewcontroller

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


I am trying to determine if a user taps on the unmute button while watching a video. I am aware of player.isMuted but I am not sure how to check if there is a change if value. I am using AVPlayerVideoViewController and want to override the unmute button functionality. This is the button I want to detect if it is tapped or not


Solution

  • I created a sample ViewController, you can observe isMuted changes easily:

    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)")
            }
        }
    }