I am using AVAudioSession with playAndRecord category as follows:
private func setupAudioSessionForRecording() {
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setActive(false)
try audioSession.setPreferredSampleRate(Double(48000))
} catch {
NSLog("Unable to deactivate Audio session")
}
let options:AVAudioSession.CategoryOptions = [.allowAirPlay, .mixWithOthers]
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.default, options: options)
} catch {
NSLog("Could not set audio session category \(error)")
}
do {
try audioSession.setActive(true)
} catch {
NSLog("Unable to activate AudioSession")
}
}
Next I use AVAudioEngine to repeat what I say in the microphone to external speakers (on the TV connected with iPhone using HDMI Cable).
//MARK:- AudioEngine
var engine: AVAudioEngine!
var playerNode: AVAudioPlayerNode!
var mixer: AVAudioMixerNode!
var audioEngineRunning = false
public func setupAudioEngine() {
self.engine = AVAudioEngine()
engine.connect(self.engine.inputNode, to: self.engine.outputNode, format: nil)
do {
engine.prepare()
try self.engine.start()
}
catch {
print("error couldn't start engine")
}
audioEngineRunning = true
}
public func stopAudioEngine() {
engine.stop()
audioEngineRunning = false
}
The issue is I hear some kind of reverb/humming noise after I speak for a few seconds that keeps getting amplified and repeated. If I use a RemoteIO unit instead, no such noise comes out of speakers. I am not sure if my setup of AVAudioEngine is correct. I have tried all kinds of AVAudioSession configuration but nothing changes.
The link to sample audio with background speaker noise is posted [here] in the Stackoverflow forum (https://stackoverflow.com/questions/72170548/echo-when-using-avaudioengine-over-hdmi#comment127514327_72170548)