I'm trying to record audio using the AudioUnit.
I have the code below: However the SetFormat method returns PropertyNotWritable. I have been able to use code like this for playing audio using the same format arguments. But can't make it work for recording audio.
(note that Xamarin seems to be missing the RemoteIO constant :( )
const int AudioUnitSubTypeRemoteIO = ('r' << 24) + ('i' << 16) + ('o' << 8) + 'c';
readonly AudioUnit.AudioUnit _audioUnit;
public AudioRecorderIos()
{
var audioComponentDescription = new AudioComponentDescription()
{
ComponentType = AudioComponentType.Output,
ComponentSubType = AudioUnitSubTypeRemoteIO,
ComponentManufacturer = AudioComponentManufacturerType.Apple,
ComponentFlags = 0,
ComponentFlagsMask = 0
};
AudioComponent defaultOutput = AudioComponent.FindNextComponent(null, ref audioComponentDescription);
_audioUnit = defaultOutput.CreateAudioUnit();
const int sampleRate = 8000;
const int channels = 1;
const int bytesPerSample = 2;
int framesPerPacket = 1;
var streamFormat = new AudioStreamBasicDescription()
{
SampleRate = sampleRate,
Format = AudioFormatType.LinearPCM,
FormatFlags = AudioFormatFlags.LinearPCMIsSignedInteger | AudioFormatFlags.IsPacked,
ChannelsPerFrame = channels,
BytesPerFrame = bytesPerSample * channels,
BitsPerChannel = bytesPerSample * 8,
BytesPerPacket = framesPerPacket * bytesPerSample * channels,
FramesPerPacket = framesPerPacket,
Reserved = 0
};
AudioUnitStatus status = _audioUnit.SetFormat(streamFormat, AudioUnitScopeType.Output);
if (status != AudioUnitStatus.OK)
{
throw new ArgumentOutOfRangeException($"Failed to set Audio Format with error {status}");
}
_audioUnit.SetRenderCallback(InputCallback, AudioUnitScopeType.Output);
_audioUnit.Initialize();
Update: if I ignore the output of SetFormat, and call GetFormat after initialising, then I get very different format options, if I then update my format request to be identical to what it chose, then I still get PropertyNotWritable. So I don't think this is related to the format values I am choosing. I have also found examples online of people using the exact same format options as I am.