方式一: 簡潔版KVO監(jiān)聽outputVolume
推薦指數(shù):??????????
小小缺點(diǎn): 音量加到最大或者最小的以后就不會(huì)再變化蛛蒙,即不會(huì)發(fā)出通知
var obs: NSKeyValueObservation?
func addVolumeObserver() {
let audioSession = AVAudioSession.sharedInstance()
do {
//打開音頻通道,這個(gè)很重要
//如果是連接了藍(lán)牙音響等外接設(shè)備的時(shí)候垒迂,在播放音樂狀態(tài)下朴爬,會(huì)自動(dòng)同步音量绰更,如果在不播放歌曲的情況下也需要同步音量议蟆,則打開音頻通道即可
try audioSession.setActive(true)
self.obs = audioSession.observe( \.outputVolume ,options: .new) { [weak self] (_, change) in
let volume = change.newValue
//音量值的范圍是0-1蒲障,如需要轉(zhuǎn)換則 (max - min)*volume 即可
guard volume != nil else{
return
}
DLog("volume \(String(describing: volume)) \(String(describing: change.oldValue))")
//self?._channel?.invokeMethod("audioVolumeChange", arguments:volume)
}
} catch {
}
}
方式二: 常規(guī)版KVO監(jiān)聽outputVolume
func addVolumeObserver() {
// 綁定音量監(jiān)聽器
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")
}
方式三:通知中心
該方式測試一直沒收到過數(shù)據(jù)
func addVolumeObserver() {
// 綁定音量監(jiān)聽器
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)
}