This project has moved and is read-only. For the latest updates, please go here.

System.IndexOutOfRangeException using WaveFileWriter

May 22, 2015 at 8:44 PM
Edited May 26, 2015 at 3:00 PM
Hi. I'm struggling with the below exception using WaveFileWriter. This exception occurs intermittently -- most times this works fine. Code snippet below:
MemoryStream s = new MemoryStream();
MemoryStream newStream = new MemoryStream();

int length = 0;
byte[] buffer = null;
int read = 0;   

MixingSampleProvider mixer2 = new MixingSampleProvider(_samples);
SampleToWaveProvider16 mixer3 = new SampleToWaveProvider16(mixer2);

length = mixer3.WaveFormat.AverageBytesPerSecond*Convert.ToInt32(position.TotalSeconds); //position is a Timespan calculated to be the total duration of the WAV files
buffer = new byte[length]; 

WaveFileWriter waveFileWriter = new WaveFileWriter(new IgnoreDisposeStream(s), mixer3.WaveFormat);

while ((read = mixer3.Read(buffer, 0, buffer.Length)) > 0)
{
    waveFileWriter.Write(buffer, 0, read);
}

waveFileWriter.Flush();
waveFileWriter.Close();
waveFileWriter.Dispose();   

s.WriteTo(newStream);
Here are the details of the Exception:

System.IndexOutOfRangeException was caught
  HResult=-2146233080
  Message=Index was outside the bounds of the array.
  Source=NAudio
  StackTrace:
       at NAudio.Wave.SampleProviders.Pcm16BitToSampleProvider.Read(Single[] buffer, Int32 offset, Int32 count)
       at NAudio.Wave.SampleProviders.OffsetSampleProvider.Read(Single[] buffer, Int32 offset, Int32 count)
       at NAudio.Wave.SampleProviders.MixingSampleProvider.Read(Single[] buffer, Int32 offset, Int32 count)
       at NAudio.Wave.SampleProviders.OffsetSampleProvider.Read(Single[] buffer, Int32 offset, Int32 count)
       at NAudio.Wave.SampleProviders.MixingSampleProvider.Read(Single[] buffer, Int32 offset, Int32 count)
       at NAudio.Wave.SampleProviders.SampleToWaveProvider16.Read(Byte[] destBuffer, Int32 offset, Int32 numBytes)
       at GamedayRadio.HalfInning.Process() in xxxxxx
  InnerException: 
Thanks in advance for any help/ideas/pointers/direction you can provide.
Jun 12, 2015 at 5:58 PM
my main suggestion would be to be sure that the number of bytes you are reading is an exact multiple of the BlockAlign. I'd probably also need to see the full signal chain and how you are using those OffsetSampleProviders to be sure.