JoelBird I assumed it was because context->audioInChannels (and therefore gInChannels) was taking from the Bela audio input rather than the number of channels in the source file.
context->audioInChannels does come from the number of physical audio inputs. Use reader.getChannels() to know the number of channels in the audio file (once you called setup() on it.
I think what you are trying to do is reading an audio file and playing it through Bela's outputs and at the same time write Bela's audio inputs to a different file. The below should do that. Note that I removed the global variables because any information about the number of input/output channels is best obtained from writer/reader after they have been initialised.
#include <Bela.h>
#include <libraries/AudioFile/AudioFile.h>
constexpr size_t kBufferSize = 32768;
AudioFileWriter writer;
AudioFileReader reader;
std::vector<float> readBuffer;
std::vector<float> writeBuffer;
const char* inPath = "./white_noise_dual_mono.wav"";
const char* outPath = "./recording.wav";
bool setup(BelaContext* context, void*)
{
int outChannels = 2; // maximum number of channels in the `writer` file
if(writer.setup(outPath, kBufferSize, outChannels, context->audioSampleRate))
{
fprintf(stderr, "Can't open output file\n");
return false;
}
if(reader.setup(inPath, kBufferSize))
{
fprintf(stderr, "Can't open input file\n");
return false;
}
readBuffer.resize(context->audioFrames * reader.getChannels());
writeBuffer.resize(context->audioFrames * writer.getChannels());
reader.setLoop(false);
return true;
}
void render(BelaContext* context, void*)
{
// playback one file
reader.getSamples(readBuffer);
for(unsigned int n = 0; n < context->audioFrames; ++n)
{
// play as many channels as possible from the audio file to the Bela output
for(unsigned int c = 0; c < context->audioOutChannels && c < reader.getChannels(); ++c)
{
float sample = readBuffer[reader.getChannels() * n + c];
audioWrite(context, n, c, 0.1 * sample);
}
// write as many channels as possible from the Bela output to the audio file
for(unsigned int c = 0; c < context->audioInChannels && c < writer.getChannels(); ++c)
{
float sample = audioRead(context, n, c);
writeBuffer[writer.getChannels() * n + c] = sample;
}
}
// write the output buffer to file
writer.setSamples(writeBuffer);
}
void cleanup(BelaContext* context, void*)
{}