I have an iOS application that uses an AVAudioSession
of category playAndRecord
and mode default
to record and play audio from and to a Bluetooth headset.
Now I want to for start and stop the recording using the buttons on the headset via MPRemoteCommandCenter
handlers.
However, the button presses on the headset especially for the pauseCommand
are not detected.
UIApplication.shared().beginReceivingRemoteControlEvents()
let audioSession = AVAudioSession.sharedInstance()
audioSession.setCategory(.playAndRecord, mode: .default, options: [.allowBluetooth])
audioSession.setActive(true)
let audioEngine = AVAudioEngine()
let audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
audioEngine.connect(audioPlayerNode, to: audioEngine.outputNode, format: nil)
audioEngine.inputNode.installTap(onBus: 0, bufferSize: 8000, format: nil) { buffer, time in
// process audio data
}
let cmdCenter = MPRemoteCommandCenter.shared()
cmdCenter.playCommand.addTarget { event in
print("registered play")
try! audioEngine.start()
return .success
}
cmdCenter.playCommand.isEnabled = true
cmdCenter.pauseCommand.addTarget { event in
// ---- THIS IS NEVER CALLED ----
print("registered pause")
audioEngine.pause()
return .success
}
cmdCenter.pauseCommand.isEnabled = true
I also published an example app showing the problem on GitHub:
https://github.com/erksch/ios-headset-record