我使用irrKlang从麦克风获得音频输入。这部分工作得很好,但我有问题将输出保存为。wav…
波文件似乎保存ok,但它似乎不播放。我想知道如果我的头是如何格式化错误:
private void SaveWave(string path, AudioFormat format, byte[] waveData)
{
//Play the audio for testing purposes
ss = engine0.AddSoundSourceFromPCMData(waveData, "sound", format);
engine0.Play2D(ss, true, false, false);
// write wave header
ushort formatType = 1;
ushort numChannels = (ushort)format.ChannelCount;
ulong sampleRate = (ulong)format.SampleRate;
ushort bitsPerChannel = (ushort)(format.SampleSize * 8);
ushort bytesPerSample = (ushort)format.FrameSize;
ulong bytesPerSecond = (ulong)format.BytesPerSecond;
ulong dataLen = (ulong)format.SampleDataSize;
const int fmtChunkLen = 16;
const int waveHeaderLen = 4 + 8 + fmtChunkLen + 8;
ulong totalLen = waveHeaderLen + dataLen;
///
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
byte[] riff = System.Text.Encoding.ASCII.GetBytes("RIFF");
bw.Write(riff);
bw.Write(totalLen);
byte[] fmt = System.Text.Encoding.ASCII.GetBytes("WAVEfmt ");
bw.Write(fmt);
bw.Write(fmtChunkLen);
bw.Write(formatType);
bw.Write(numChannels);
bw.Write(sampleRate);
bw.Write(bytesPerSecond);
bw.Write(bytesPerSample);
bw.Write(bitsPerChannel);
byte[] data = System.Text.Encoding.ASCII.GetBytes("data");
bw.Write(data);
bw.Write(waveData.Length);
bw.Write(waveData);
bw.Close();
fs.Close();
}
你写错了string
头。
BinaryWriter.Write(string)
不适合这样写。根据这篇msdn文章,它在写入前将其长度前缀为string
。
您需要将这些头写入bytes
。
像这样做,
byte[] riff= System.Text.Encoding.ASCII.GetBytes("RIFF");
bw.Write(riff);
byte[] fmt = System.Text.Encoding.ASCII.GetBytes("WAVEfmt ");
bw.Write(fmt);
// Remove the space in "data " to "data"
//byte[] data= System.Text.Encoding.ASCII.GetBytes("data ");
byte[] data= System.Text.Encoding.ASCII.GetBytes("data");
bw.Write(data);
其余的标题看起来很好。
希望这对你有帮助