首页 > 解决方案 > 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: ()
    }
}

标签: iosswiftbluetoothavaudiosession

解决方案


推荐阅读