I have a project where I am trying to get my bluetooth headphones to work. In my view controller I add routeChangeNotification
to see what is going on and it fires twice (both with case .categoryChange
. The first time it shows my bluetooth headphones and then the second time it fires it reverts back to device microphone.
In AppDelegate I have:
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)
}
In my ViewController I have:
@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: ()
}
}