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

Different sample values from WaveStream vs WaveFileReader

Apr 28, 2011 at 8:32 PM

Hi Experts! 

First let me say I've enjoyed using the NAudio library!  I have a question though about getting sample values for doing an FFT.  I've checked the sample values on a wav file by using the following method:

double[] array = new double[512];
while (reader.HasData(array.Length) && currentSampleIndex < currentSamples.Length)
 {
     reader.TryReadFloat(ref nextSample);
     currentSamples[currentSampleIndex++] = nextSample;
     if (reader.WaveFormat.Channels > 1)
     {
           reader.TryReadFloat(ref nextSample);
      }

}

This works great and gives me the correct sample values for the wav file.  I'm working on building a spectrum analyzer so I want to get the audio samples as the audio is playing.  So I've modified the MeteringStream example to try and accomplish my needs by for some reason the sample values are not matching what they should be.  Here's the code:

public override int Read(byte[] buffer, int offset, int count)
{          
    int bytesRead = SourceStream.Read(buffer, offset, count);
    ProcessData(buffer, offset, bytesRead);
    return bytesRead;
}

private void ProcessData(byte[] buffer, int offset, int count)
{
    int index = 0;
    while (index < count)
    {
    float sampleValue = Math.Abs(BitConverter.ToSingle(buffer, offset + index));
    currentSamples[sampleIndex] = sampleValue;
    index += 4;

    if (SourceStream.WaveFormat.Channels == 2)
    {
        float sampleRightValue = Math.Abs(BitConverter.ToSingle(buffer, offset + index));
        index += 4;
    }

    sampleIndex++;

    if (sampleIndex >= currentSamples.Length)
    {
        RaiseSampleStreamNotification();
        sampleCount = 0;
        sampleIndex = 0;
        Array.Clear(currentSamples, 0, currentSamples.Length);
    }
    }
}

The audio I'm using is a Tone wav file that has two channels of audio - I'm only interested in the left channel.  The sample rate is 48K and the bits per sample is 16.  If I haven't provided enough information please let me know.  Any information you can give me would be much appreciated!

 

Apr 28, 2011 at 8:35 PM

have you looked at the WpfDemo that comes with NAudio - that includes an FFT being used for a spectrum analyser

Apr 29, 2011 at 2:39 PM

Hi Mark!

Yes I had looked at that example but had given up on using it because the WaveChannel32 input stream class I was using didn't have Sample object shown in the example.  I gave it another try yesterday (and updated my NAudio version) and was able to get everything working!  Thanks for your help!