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

大兔子大兔子 提交于 2019-11-28 01:07:25

问题


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 ?


回答1:


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();


来源:https://stackoverflow.com/questions/12075062/saving-each-wav-channel-as-a-mono-channel-wav-file-using-naudio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!