write byte array to wav file c#

  • 1166
  • 0

write byte array to wav file c#

Using NAudio package, it'll be something like:


var wav1Reader = new WaveFileReader(yourWavFilePath);

byte[] buffer = new byte[2 * wav1Reader.WaveFormat.SampleRate * wav1Reader.WaveFormat.Channels];

using (	WaveFileWriter writer = new WaveFileWriter(YourOutputFilePath, new WaveFormat(wav1Reader.WaveFormat.SampleRate, 16, 2/*how many channel*/))
	)
{
	int bytesRead;
	while ((bytesRead = waveProvider.Read(buffer, 0, buffer.Length)) > 0)
	{
		writer.WriteData(buffer, 0, bytesRead);
	}
}

 

The commented version:


//var wavReader = new WaveFileReader(yourWavFilePath);
//byte[] buffer = new byte[2 * wav1Reader.WaveFormat.SampleRate * wav1Reader.WaveFormat.Channels];
byte[] buffer = YourWaveSoundByteArray;

using ( WaveFileWriter writer = new WaveFileWriter(YourOutputFilePath, new WaveFormat( AssignWaveFormatYouWant /*wavReader.WaveFormat.SampleRate, 16, 2/*how many channel*/))
    )
{
    //int bytesRead;
    //while ((bytesRead = wavReader.Read(buffer, 0, buffer.Length)) > 0)
    //{
        writer.Write(buffer, 0,  buffer.Length/*bytesRead*/);
    //}
}

 

 

Additional Info:

1. more introduction of WaveFileWriter see http://mark-dot-net.blogspot.tw/2011/04/how-to-use-wavefilewriter.html

 

2.

WriteData() is marked as  [Obsolete("Use Write instead")] , so use Write() method might be better.

I go to find the source code here, 

https://github.com/naudio/NAudio/blob/d7767282459b2b9e3d648f51a0879d719dda26d0/NAudio/Wave/WaveOutputs/WaveFileWriter.cs

and at this moment if you use WriteData() , it actually call the  Write() method.