ios - AVAudioSession.routeChangeNotification 蓝牙耳机断开
问题描述
我有一个项目,我试图让我的蓝牙耳机工作。在我的视图控制器中,我添加routeChangeNotification
以查看发生了什么,它会触发两次(都带有 case .categoryChange
。第一次它显示我的蓝牙耳机,然后第二次触发它会恢复到设备麦克风。
在 AppDelegate 我有:
let session = AVAudioSession.sharedInstance()
do {
// https://stackoverflow.com/questions/51010390/avaudiosession-setcategory-swift-4-2-ios-12-play-sound-on-silent
if #available(iOS 10.0, *) {
try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])
} else {
session.perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playAndRecord, with: [
AVAudioSession.CategoryOptions.allowBluetooth,
AVAudioSession.CategoryOptions.defaultToSpeaker]
)
try session.setMode(.default)
}
try session.setActive(true)
} catch {
print(error)
}
在我的 ViewController 我有:
@objc private func didRouteChangeNotification(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let reasonValue = userInfo[AVAudioSessionRouteChangeReasonKey] as? UInt, let reason = AVAudioSession.RouteChangeReason(rawValue:reasonValue) else {
return
}
switch reason {
case .newDeviceAvailable:
debugPrint("newDeviceAvailable")
case .oldDeviceUnavailable:
debugPrint("oldDeviceUnavailable")
case .categoryChange:
debugPrint("catgoryChange")
default: ()
}
}
解决方案
推荐阅读
- android - 使用 Mockk 模拟采用 lambda 的私有函数
- python - 如何查看 sqlite3 Python 模块在 Ubuntu 16.04 上使用的 sqlite3 二进制文件?
- spring - Spring Boot Rest API ResponseStatusException 中的异常处理
- excel - 使用 switch 函数查询请求参数值
- python - 递归函数转换
- python-3.x - 在 seaborn 库中绘制 Lineplot 时遇到问题
- python - Django:经过身份验证的用户的相关对象
- python - Python - 匹配除了换行符之外没有空格的字符串?
- java - 这是我的第一个 servlet 程序,我有问题
- python - Python 为 Selenium 导入 Chrome Webdriver