I'm using AUAudioUnit to play audio that the app is streaming from the server. My code works fine in the foreground. But when I background the app, it won't play the audio. I got the following error.
[aurioc] AURemoteIO.cpp:1590:Start: AUIOClient_StartIO failed (561145187)
The error code 561145187 means AVAudioSessionErrorCodeCannotStartRecording
This error type usually occurs when an app starts a mixable recording from the background and it isn’t configured as an Inter-App Audio app.
This is how I set up the AVAudioSession in Swift:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .voiceChat, options: [.allowBluetooth])
This is how I set up the AUAudioUnit in Objective-C:
AudioComponentDescription description;
description.componentType = kAudioUnitType_Output;
description.componentSubType = kAudioUnitSubType_VoiceProcessingIO;
description.componentManufacturer = kAudioUnitManufacturer_Apple;
description.componentFlags = 0;
description.componentFlagsMask = 0;
self.format = [[AVAudioFormat alloc] initWithSettings: @{
AVFormatIDKey: @(kAudioFormatLinearPCM),
AVSampleRateKey: @16000,
AVNumberOfChannelsKey: @1,
AVLinearPCMIsFloatKey: @NO,
AVLinearPCMBitDepthKey: @16,
AVLinearPCMIsBigEndianKey: @NO
}];
self.audioUnit = [[AUAudioUnit alloc] initWithComponentDescription:description options:0 error:nil];
When I call the startHardwareAndReturnError
method, that's when I get that error message.
[self.unit startHardwareAndReturnError:outError];
I already set the Background Modes - Audio capability. And I'm pretty sure I set up the AVAudioSession so it's non-mixable. I'm not even recording. I'm just trying to play the audio. What else am I missing?
To record audio in the background, you have to start the audio unit in the foreground. Then the audio unit will continue to run in the background. If you don't have any data to play, you can play silence.
If you are not recording audio, then don't use the playAndRecord session type. Use one of the play-only session types instead.