美文网首页
iOS 监听系统音量变化

iOS 监听系统音量变化

作者: 沫简影 | 来源:发表于2023-02-13 10:50 被阅读0次

方式一: 简洁版KVO监听outputVolume
推荐指数:⭐️⭐️⭐️⭐️⭐️
小小缺点: 音量加到最大或者最小的以后就不会再变化,即不会发出通知

 var obs: NSKeyValueObservation?
 func addVolumeObserver() {
        let audioSession = AVAudioSession.sharedInstance()
        do {
          //打开音频通道,这个很重要
          //如果是连接了蓝牙音响等外接设备的时候,在播放音乐状态下,会自动同步音量,如果在不播放歌曲的情况下也需要同步音量,则打开音频通道即可
            try audioSession.setActive(true)
            
            self.obs = audioSession.observe( \.outputVolume ,options: .new) { [weak self] (_, change) in
                let volume = change.newValue
                //音量值的范围是0-1,如需要转换则 (max - min)*volume 即可
                guard volume != nil else{
                    return
                }
                DLog("volume \(String(describing: volume)) \(String(describing: change.oldValue))")
                //self?._channel?.invokeMethod("audioVolumeChange", arguments:volume)
            }
        } catch  {
            
        }
    }

方式二: 常规版KVO监听outputVolume

  func addVolumeObserver() {
        // 绑定音量监听器
        let audioSession = AVAudioSession.sharedInstance()
        do {
            try audioSession.setActive(true)
            
            audioSession.addObserver(self, forKeyPath: "outputVolume",options: .new,context: nil)
        } catch  {
            
        }
    }

  public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "outputVolume"{
            guard let newKey = change?[NSKeyValueChangeKey.newKey] as? NSNumber else {
                fatalError("Could not unwrap optional content of new key")
            }

            let volume = newKey.floatValue

            print("volume " + volume.description)
        }
    }

 deinit {
        //self.obs?.invalidate()
        AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: "outputVolume")
    }

方式三:通知中心
该方式测试一直没收到过数据

func addVolumeObserver() {
      // 绑定音量监听器
      if #available(iOS 15, *) {
          NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "SystemVolumeDidChange"), object: nil)
      }
      else {
          NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
      }
      UIApplication.shared.beginReceivingRemoteControlEvents();
  }
  
  @objc private func volumeChanged(_ noti: NSNotification) {

      if let userInfo = noti.userInfo {
          if #available(iOS 15, *) {
              let volume = userInfo["Volume"] as? Float
              print("volume: \(String(describing: volume))")
          }
          else {
              let volume = userInfo["AVSystemController_AudioVolumeNotificationParameter"] as? Float
              print("volume: \(String(describing: volume))")
          }
      }
  }
  
  deinit {
      DLog("SwiftLotBluetoothPlugin dealloc")
      NotificationCenter.default.removeObserver(self)
  }

相关文章

网友评论

      本文标题:iOS 监听系统音量变化

      本文链接:https://www.haomeiwen.com/subject/alvjkdtx.html