'AVAudioEngine input tap with Background Mode
I have an application that needs to buffer data from the microphone while in background mode. I have enabled background mode for 'Audio, Airplay and Picture in Picture'.
When the app moves to the background I can see the orange indicator in the top left of my iPhone for around 10 seconds before it disappears and buffering stops.
Does background mode only support AVAudioRecorder? Or could it be another problem like an object going out of scope? Any ideas gratefully accepted.
The following code is within a singleton class and called within the app's initialiser.
let audioSession = AVAudioSession.sharedInstance()
let audioEngine = AVAudioEngine()
private var audioBuffer = [Float]() {
didSet {
if audioBuffer.count > bufferSize {
audioBuffer.remove(at: 0)
}
}
}
public func installTap() {
do {
try audioSession.setCategory(AVAudioSession.Category.playAndRecord)
try audioSession.setActive(true)
} catch {
print("Error setting up audio session: \(error)")
}
let inputNode = audioEngine.inputNode
self.inputFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: UInt32(sampleRate/10), format: inputFormat) { buff, time in
let sampleCount = Int(buff.frameLength)
var sampleIndex = 0
while sampleIndex < sampleCount {
if let sample = buff.floatChannelData?.pointee[sampleIndex] {
if self.isBuffering {
self.audioBuffer.append(sample)
}
sampleIndex += 1
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
