Simple waveform visualizing

Jan 10, 2012 at 1:01 PM

I have been browsing through this forum and the demo NAudio project for several hours now but I'm still unable to understand how to simply draw a waveform. The example provided is in C#, which is a bit unfamiliar to me. I just can't figure out where to start.. I'd greatly appreciate your help on getting me started.

Coordinator
Jan 24, 2012 at 12:18 PM

The way to draw a waveform is to examine sample values over a set period (say 200ms), and pick out the highest and lowest values. Then draw a vertical line representing that time. Then move on to the next one. That is how the waveform drawing in NAudio works.

Feb 1, 2012 at 8:25 AM

But how do I examine the values? I am able to play the file, but can't extract the amplitude value. I also can't figure out how to create a buffer and read from there. I sort of have it all in my mind, but can't put it down in code..

Feb 1, 2012 at 10:43 AM

I'm using WaveViewer to show wave file while playback and WavePainter to show waveFile while recording. And in some my post on this forum I have described everything.

Use dataAvailable event:

private void input_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{   
  if (OnVolumePeak != null)
  {
    float max = 0;
    float min = 0;

    for (int index = 0; index < e.BytesRecorded; index += 2)
    {
      short sample = (short)((e.Buffer[index+1]<<8) | (e.Buffer[index]) );
      float sample32 = sample / 32768f;

      max = Math.Max(sample32, max);
      min = Math.Min(sample32, min);
    }

    OnVolumePeak(this, max, min);

  }

  if (_state == State.RECORDING)
  {
    if (waveWriter != null)
    {
      waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
      waveWriter.Flush();
    }

    memStream.Write(e.Buffer, 0, e.BytesRecorded);
  }
            
}

 

OnVolumePeak is my event. You can treat is as an ordinary method.

It looks like that:

public void am_OnVolumePeak(object Sender, float max, float min)
{
  max = Math.Max(max, Math.Abs(min));
  wavePainter.AddMax(max);
}

 

When you want to show waveform of existing wave file, WaveViewer has a property called WaveStream.

Feb 2, 2012 at 10:51 AM

Thank you, but I can't figure out where to get the waveWriter or memstream..

Coordinator
Feb 2, 2012 at 7:28 PM

they are instances of WaveFileWriter (part of NAudio) and MemoryStream (part of .NET framework)