How to read the data in a wav file to an array

后端 未结 7 2051
清酒与你
清酒与你 2020-11-27 15:17

I need to get all the samples of a wav file into an array (or two if you need to do that to keep the stereo) so that I can apply some modifications to them. I was wondering

7条回答
  •  生来不讨喜
    2020-11-27 16:03

    Assuming your WAV file contains 16 bit PCM (which is the most common), you can use NAudio to read it out into a byte array, and then copy that into an array of 16 bit integers for convenience. If it is stereo, the samples will be interleaved left, right.

    using (WaveFileReader reader = new WaveFileReader("myfile.wav"))
    {
        Assert.AreEqual(16, reader.WaveFormat.BitsPerSample, "Only works with 16 bit audio");
        byte[] buffer = new byte[reader.Length];
        int read = reader.Read(buffer, 0, buffer.Length);
        short[] sampleBuffer = new short[read / 2];
        Buffer.BlockCopy(buffer, 0, sampleBuffer, 0, read);
    }
    

    I know you wanted to avoid third party libraries, but if you want to be sure to cope with WAV files with extra chunks, I suggest avoiding approaches like just seeking 44 bytes into the file.

提交回复
热议问题