c#将短数组从单声道wav文件转换为短数组以写为立体声wav

时间:2014-01-20 00:09:46

标签: c# audio windows-phone wav

这可能是一个非常简单的问题;我将单声道WAV文件转换为short []数组,我有一个函数将其写回WAV文件。一切都很好。 (writeBuffer是short []数组)

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

我的问题是我需要对那个短数组做什么才能把它写成立体声文件;如果我写入我的WAV标题,WAV有2个频道(现在我正在写它有1个),通过更改以下行:

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

我需要对short []数组做什么?例如,将每一个元素视为第二个通道的一部分吗?所以我需要创建一个short []的writeBuffer.Length * 2,然后将writeBuffer的每个值写入新数组:

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];
}
这是正确的吗?或者我是否就如何为立体声文件和单声道文件编写short []数组做出错误的假设?

1 个答案:

答案 0 :(得分:1)

将您的代码更改为:

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];
}