Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving each WAV channel as a mono-channel WAV file using Naudio

I'm trying to convert a WAV file(PCM,48kHz, 4-Channel, 16 bit) into mono-channel WAV files.

I tried splittiing the WAV file into 4 byte-arrays like this answer and created a WaveMemoryStream like shown below but does not work.

byte[] chan1ByteArray = new byte[channel1Buffer.Length];
Buffer.BlockCopy(channel1Buffer, 0, chan1ByteArray, 0, chan1ByteArray.Length);
WaveMemoryStream chan1 = new WaveMemoryStream(chan1ByteArray, sampleRate, (ushort)bitsPerSample, 1);

Am I missing something in creating the WAVE headers ? Or is there more to splitting a WAV into mono channel WAV files ?

like image 868
CharlesBryan Avatar asked Aug 22 '12 14:08

CharlesBryan


1 Answers

The basic idea is that the source wave file contains the samples interleaved. One for the first channel, one for the second, and so on. Here's some untested example code to give you an idea of how to do this.

var reader = new WaveFileReader("fourchannel.wav");
var buffer = new byte[2 * reader.WaveFormat.SampleRate * reader.WaveFormat.Channels];
var writers = new WaveFileWriter[reader.WaveFormat.Channels];
for (int n = 0; n < writers.Length; n++) 
{
    var format = new WaveFormat(reader.WaveFormat.SampleRate,16,1);
    writers[n] = new WaveFileWriter(String.Format("channel{0}.wav",n+1), format);
}
int bytesRead;
while((bytesRead = reader.Read(buffer,0, buffer.Length)) > 0) 
{
    int offset=  0;
    while (offset < bytesRead) 
    {
        for (int n = 0; n < writers.Length; n++) 
        {
            // write one sample
            writers[n].Write(buffer,offset,2);
            offset += 2;
        }           
    }
}
for (int n = 0; n < writers.Length; n++) 
{
    writers[n].Dispose();
}
reader.Dispose();
like image 106
Mark Heath Avatar answered Sep 19 '22 06:09

Mark Heath