Kamran Rastegar Kamran Rastegar - 1 month ago 12
C# Question

c# converting short array from mono wav file, to short array to write as stereo wav

This may be a really simple question; I converted a mono WAV file to a short[] array, and I have a function that writes this back to a WAV file. all works good. (writeBuffer is the short[] array)

byte[] dataBuffer = new byte[writeBuffer.Length * 2];
Buffer.BlockCopy(writeBuffer, 0, dataBuffer, 0, dataBuffer.Length);

using (var targetFile = isoStore.CreateFile("temp.wav"))
{
WriteHeader(targetFile, (int)dataBuffer.Length, 1, SamplesPerSecond);
int start = 0;
targetFile.Write(dataBuffer, start, (int)dataBuffer.Length);
targetFile.Flush();
targetFile.Close();
}


My question is what I need to do to that short array in order to have it written as a stereo file; If I write to my WAV header that the WAV has 2 channels (right now I am writing it has 1), by changing the following line:

WriteHeader(targetFile, (int)dataBuffer.Length, 2, SamplesPerSecond);


what do I need to do to my short[] array? will, for example, every second element be treated as part of the second channel? so would I need to create a short[] of writeBuffer.Length*2, and then write each value of writeBuffer to the new array as such:

short[] newBuffer = new short[writeBuffer.Length*2];
for (int i=0; i< newBuffer.Length;i = i + 2)
{
newBuffer[i] = writeBuffer[i];
newBuffer[i+1] = writeBuffer[i];
}


would this be correct? Or am I making an incorrect assumption about how the short[] array is to be written for a stereo file versus a mono file?

Answer

Change your code to:

short[] newBuffer = new short[writeBuffer.Length*2];
int index = offset; //offset might be 0
for (int i=0; i< newBuffer.Length;i = i + 2)
{
    newBuffer[index++] = writeBuffer[i];
    newBuffer[index++] = writeBuffer[i];
}
Comments