I’ve got a ByteArrayOutputStream of stereo audio data. Currently I’m doing this, which I know is bad:
WaveFileWriter wfw = new WaveFileWriter();
AudioFormat format = new AudioFormat(Encoding.PCM_SIGNED, 44100, 16, 1, 2, 44100, false);
byte[] audioData = dataout.toByteArray(); //bad bad bad
int length = audioData.length;
byte[] monoData = new byte[length/2]; //bad bad bad
for(int i = 0; i < length; i+=4){
monoData[i/2] = audioData[i];
monoData[1+i/2] = audioData[i+1];
}
ByteArrayInputStream bais = new ByteArrayInputStream(monoData);
AudioInputStream outStream = new AudioInputStream(bais,format,length);
wfw.write(outStream, Type.WAVE,output);
What’s a better way of doing this? Can I convert the ByteArrayOutputStream into a ByteArrayInputStream so that I can read from it?
Edit
Ok so I’ve dug into the class that’s giving me the ByteArrayOutputStream I’m working with. It’s being populated with a call to:
dataout.write(convbuffer, 0, 2 * vi.channels * bout);
I can swap this out for something else if it’ll help, but what should I use?
I tried replacing it with:
for(int j = 0;j < bout; j += 2){
dataout.write(convbuffer,2*j,2);
}
but that didn’t work, not sure why.
Can’t you read audio data by one sample at a time, and write the samples to the file as you read them?
Also it seems that your current code overwrites— Thanks for the correction, @fredley.monoDatapointlessly.State what you’re doing in plain English first; this will help you understand it, and then turn to code.