Creating a .wav File in C#

前端 未结 4 1308
青春惊慌失措
青春惊慌失措 2021-02-05 15:25

As an excuse to learn C#, I have been trying to code a simple project: creating audio files. To start, I want to make sure that I can write files that meet the WAVE format. I ha

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-05 15:42

    The major problem is:

    BinaryWriter.Write(string) writes a string that is prefixed with it's length for BinaryReader to read it back. It is not intended to be used like your case. You need to write the bytes directly instead of using BinaryWriter.Write(string).

    What you should do:

    Convert the string into bytes and then write the bytes directly.

    byte[] data = System.Text.Encoding.ASCII.GetBytes("RIFF");
    binaryWriter.Write(data);
    

    or make it one line:

    binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));
    

    There may also be other problems, like the integers you are writing may not be of the same size as required. You should check them carefully.

    As for endianess, the link you put states that data are in little-endian and BinaryWriter uses little-endian, so this should not be a problem.

提交回复
热议问题