Testing on real device iPhone 6s, iOS 15, headphones, Xcode Version 13.1 (13A1030d). Also click noise when audioUnit.stopHardware(). Clicking even if the callback buffer is filled with zeros or AudioCallback = {}. Clicking when init() and also if called at runtime. Click is not loud but it is audible. Sound is click free otherwise. This code is the init() of a singleton audio class.
init() {
do {
print("Initializing ToneGenerator.")
audioSession = AVAudioSession.sharedInstance()
try audioSession.setPreferredIOBufferDuration(512 * 2 / audioSession.sampleRate)
try audioSession.setCategory(AVAudioSession.Category.ambient) // , options: AVAudioSession.CategoryOptions())
try audioSession.setActive(true)
} catch let error { print("Creating audio session failed with error: \(error.localizedDescription)"); assert(false) }
sampleRate = audioSession.sampleRate
ioBufferDuration = audioSession.ioBufferDuration
framesPerBuffer = Int(round(ioBufferDuration * sampleRate)) // round() is faster to type check than .rounded().
print("audioSession.sampleRate = \(sampleRate)")
print("audioSession.ioBufferDuration = \(audioSession.ioBufferDuration)")
print("ioBufferDuration * sampleRate = frames per buffer = \(ioBufferDuration * sampleRate)")
let audioComponentDescription = AudioComponentDescription(
componentType: kAudioUnitType_Output,
componentSubType: kAudioUnitSubType_RemoteIO,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0, componentFlagsMask: 0 )
do {
try audioUnit = AUAudioUnit(componentDescription: audioComponentDescription) // On my iPhone 6s this gives error: IPCAUClient.cpp:139:ConnectToRegistrationServer: IPCAUClient: can't connect to server (-66748)
let audioFormat = AVAudioFormat(
commonFormat: AVAudioCommonFormat.pcmFormatInt16,
sampleRate: Double(sampleRate),
channels:AVAudioChannelCount( 2 ),
interleaved: true )!
try audioUnit.inputBusses[0].setFormat(audioFormat)
audioUnit.outputProvider = AudioCallback
audioUnit.isOutputEnabled = true // Default is true.
try audioUnit.allocateRenderResources() // v2 AudioUnitInitialize()
try audioUnit.startHardware() // v2 AudioOutputUnitStart()
} catch let error { print("Creating audio unit failed with error: \(error.localizedDescription)"); assert(false) }
}