保存.wav文件后出错

时间:2016-06-28 05:07:36

标签: c# .net filestream wave irrklang

我正在使用irrKlang从麦克风获取音频输入。那部分效果很好,但我在输出保存为.wav时遇到了问题...

wave文件似乎保存正常,但似乎没有播放。我想知道我的标题是否有些格式错误:

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

1 个答案:

答案 0 :(得分:0)

您正在编写string标头错误。

BinaryWriter.Write(string)不适合这样写作。根据这个msdn article,它在写入之前将它的长度加到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);

其余的标题似乎很好。

希望这有助于你