如何检测iOS中的音量变化?

问题描述 投票:0回答:2

我已经阅读了stackOverFlow和gitHub提供的很多解决方案,但它们对我都不起作用。我尝试了以下两种方式:

  1. 使用audioSession
override func viewWillAppear(_ animated: Bool) {
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(true, options: [])
        } catch {
            print("error")
        }
        // this print shows, got the current volume.
        //but what I need is the notification of the change of volume
        print("view will appear ,this volume is \(audioSession.outputVolume)")
        audioSession.addObserver(self,
                                 forKeyPath: "outputVolume",
                                 options: [.new],
                                 context: nil)
    }

override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        if keyPath == "outputVolume"{
            let audioSession = AVAudioSession.sharedInstance()
            let volume = audioSession.outputVolume
            //this print doesn't shows up
            print("observed volume is \(volume)")
        }
    }
  1. 使用通知
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(observed(_:)), name: Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
    }

    @objc func observed(_ notification: Notification){
        print("observed")
    }

顺便说一下,我正在使用模拟器(iPhone11,iOS13.1),Xcode版本是11.1

ios swift volume detect
2个回答
1
投票

您需要确保您应用的音频会话处于活动状态,才能正常工作:


0
投票

尝试使用以下内容:

© www.soinside.com 2019 - 2024. All rights reserved.