使用下面的代码,我得到了输出音量,但它确实不一致 - 有时它给出相同的值,有时它是后面的音量变化,尽管系统音量实际上正确变化。
有什么方法可以让它每次都输出正确的值吗?
func viewDidLoad() {
...
NotificationCenter.default.addObserver(self, selector: #selector(volumeDidChange), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
...
}
func volumeDidChange() {
print("VOLUME CHANGING", AVAudioSession.sharedInstance().outputVolume)
// output while changing the volume with hardware buttons
VOLUME CHANGING 0.0625
VOLUME CHANGING 0.0625
VOLUME CHANGING 0.125
VOLUME CHANGING 0.1875
VOLUME CHANGING 0.25
VOLUME CHANGING 0.375
VOLUME CHANGING 0.375
VOLUME CHANGING 0.4375
VOLUME CHANGING 0.5
VOLUME CHANGING 0.5625
VOLUME CHANGING 0.625
VOLUME CHANGING 0.6875
VOLUME CHANGING 0.75
VOLUME CHANGING 0.8125
VOLUME CHANGING 0.875
VOLUME CHANGING 0.75
VOLUME CHANGING 0.6875
VOLUME CHANGING 0.625
VOLUME CHANGING 0.625
VOLUME CHANGING 0.5625
VOLUME CHANGING 0.5
VOLUME CHANGING 0.4375
VOLUME CHANGING 0.375
VOLUME CHANGING 0.3125
VOLUME CHANGING 0.375
VOLUME CHANGING 0.4375
VOLUME CHANGING 0.4375
尝试
import AVFoundation
import MediaPlayer
//MARK: Did Load
override func viewDidLoad() {
super.viewDidLoad()
/// Volume View
let volumeView = MPVolumeView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
volumeView.isHidden = false
volumeView.alpha = 0.01
view.addSubview(volumeView)
/// Notification Observer
NotificationCenter.default.addObserver(self, selector: #selector(self.volumeDidChange(notification:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
}
@objc func volumeDidChange(notification: NSNotification) {
//print("VOLUME CHANGING", AVAudioSession.sharedInstance().outputVolume)
let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as! Float
print("Device Volume:\(volume)")
}
您当前的输出 - 相同的值不断重复
所需输出
override func viewDidLoad() {
super.viewDidLoad()
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(true)
} catch {
print("error in getting volume")
}
if session.outputVolume < 1.0 {
volumeButton = 0
} else {
volumeButton = 1
}
NotificationCenter.default.addObserver(self, selector: #selector(self.volumeDidChange(notification:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
}
@objc func volumeDidChange(notification: NSNotification) {
if let volume = notification.userInfo?["AVSystemController_AudioVolumeNotificationParameter"] as? Float{
print("Device Volume:\(volume)")
} else{
print("Error while reading value...")
}
}
几乎同样的问题,sirikit Intent 只在第一次获取音量。如果快捷方式脚本多次使用意图,则第二次意图返回与第一次返回相同的音量级别,尽管事实上,音量在两次意图调用之间(通过应用程序意图的两次音量请求之间)发生了变化。以上任何内容在 Siri 套件中都不适合我。