Skip to content

Instantly share code, notes, and snippets.

@nevosegal
Created October 8, 2019 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevosegal/5669ae8fb6f3fba44505543e43b5d54b to your computer and use it in GitHub Desktop.
Save nevosegal/5669ae8fb6f3fba44505543e43b5d54b to your computer and use it in GitHub Desktop.
Simple way to reproduce iOS bug - connecting Bluetooth Headphones while app is backgrounded.
//
// AppDelegate.swift
// ios-bluetooth-bug
//
// Created by Nevo Segal on 08/10/2019.
//
import UIKit
import AVFoundation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
let audioEngine = AVAudioEngine()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
do {
try AVAudioSession.sharedInstance().setCategory(.playAndRecord,
mode: .default,
options: [.allowBluetoothA2DP,
.mixWithOthers,
.defaultToSpeaker,
.allowAirPlay])
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error.localizedDescription)
}
setup()
start()
NotificationCenter.default.addObserver(self, selector: #selector(handleConfigurationChange), name: .AVAudioEngineConfigurationChange, object: nil)
return true
}
@objc func handleConfigurationChange() {
//attempt to call start()
//or to audioEngine.reset(), setup() and start()
//or any other combination that involves starting the audioEngine
//results in an error 561145187.
//Not calling start() doesn't return this error, but also doesn't restart
//the recording.
print("received configration change notification")
audioEngine.reset()
audioEngine.inputNode.removeTap(onBus: 0)
setup()
start()
}
public func setup() {
//Setup nodes
let inputNode = audioEngine.inputNode
let inputFormat = inputNode.inputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 4096, format: inputFormat) { (buffer, _) -> Void in
//Do audio conversion and use buffers
}
}
public func start() {
guard !audioEngine.isRunning else {
print("Audio Engine is already running")
return
}
do {
audioEngine.prepare()
try audioEngine.start()
} catch {
print("Unable to start audio engine \(error.localizedDescription)")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment