1

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

波形文件似乎可以保存,但似乎无法播放。我想知道我的标题是否格式错误:

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

1 回答 1

0

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

其余的标题似乎很好。

希望这可以帮助你

于 2016-06-28T05:31:17.633 回答