ios - iOS中如何检测音量变化?

标签 ios swift volume detect

我阅读了 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)")
        }
    }
  • 使用通知
  •     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

    最佳答案

    尝试使用以下内容:

    import UIKit
    import MediaPlayer
    import AVFoundation
      
    class ViewController: UIViewController {
      
        private var audioLevel: Float = 0.0
    
        deinit {
            audioSession.removeObserver(self, forKeyPath: "outputVolume")
        }
          
        override func viewDidLoad() {
            super.viewDidLoad()
        }
          
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            listenVolumeButton()
        }
          
        func listenVolumeButton() {
              
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(true, options: [])
                audioSession.addObserver(self, forKeyPath: "outputVolume",
                                         options: NSKeyValueObservingOptions.new, context: nil)
                audioLevel = audioSession.outputVolume
            } catch {
                print("Error")
            }
        }
          
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == "outputVolume" {
                let audioSession = AVAudioSession.sharedInstance()
                if audioSession.outputVolume > audioLevel {
                    print("Hello")
                    audioLevel = audioSession.outputVolume
                }
                if audioSession.outputVolume < audioLevel {
                    print("Goodbye")
                    audioLevel = audioSession.outputVolume
                }
                if audioSession.outputVolume > 0.999 {
                    (MPVolumeView().subviews.filter { NSStringFromClass($0.classForCoder) == "MPVolumeSlider" }.first as? UISlider)?.setValue(0.9375, animated: false)
                    audioLevel = 0.9375
                }
                  
                if audioSession.outputVolume < 0.001 {
                    (MPVolumeView().subviews.filter { NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(0.0625, animated: false)
                    audioLevel = 0.0625
                }
            }
        }
    }
    

    希望这对您有帮助!

    关于ios - iOS中如何检测音量变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58975844/

    相关文章:

    ios - Xcode UIView 随机调整大小

    ios - 如何将托管对象上下文分配给 iOS 中的应用程序委托(delegate)?

    javascript - iOS 文本区域在滚动后停止工作

    swift - 使用 Fluent 保存两个模型并从数据库中检索记录时出现问题

    swift - Swift 运算符的类型和调用

    ubuntu - 在启动时设置 Ubuntu 音量

    android - Android API 23 中删除了 Settings.System.VOLUME_SETTINGS?

    javascript - 捕获浏览器的音量事件

    ios - iTunes Connect:带有特殊字符的公司名称

    ios - 确定应用程序是否在 iPhone 6 键盘上以 "scaled"模式运行?