title: NAudio Peak Volume Meter
body: <p>I'm attempting to write a peak volume meter using NAudio. My code is very similar to <a href="http://channel9.msdn.com/coding4fun/articles/NET-Voice-Recorder" rel="nofollow">http://channel9.msdn.com/coding4fun/articles/NET-Voice-Recorder</a>, but both my code and the linked Voice Recorder project suffer from an issue.</p>
  
  <p>When playing a sound of constant frequency and volume, the volume meter initially begins at a reasonable level, but then decays to a very small value. I'm not sure why this is the case, for the peak volume meter in the NAudioDemo does not do this. I attempted to replicate the code from NAudioDemo in my program, but I was unable to find the code file containing the peak volume meter code.</p>
  
  <p>Can somebody guide me to an alternative solution for creating a peak volume meter or help me determine why my solution (and the one provided at the link) both don't work?</p>
  
  <pre><code>public MainWindow()
      {
          int waveInDevices = WaveIn.DeviceCount;
          for (int waveInDevice = 0; waveInDevice &lt; waveInDevices; waveInDevice++)
          {
              WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
              Console.WriteLine("Device {0}: {1}, {2} channels",
                  waveInDevice, deviceInfo.ProductName, deviceInfo.Channels);
  
              WaveIn waveIn = new WaveIn();
              waveIn.DeviceNumber = 0; //TODO: Let the user choose which device, this comes from the device numbers above
              waveIn.DataAvailable += waveIn_DataAvailable;
              int sampleRate = SAMPLE_RATE; // 8 kHz
              int channels = 1; // mono
              waveIn.WaveFormat = new WaveFormat(sampleRate, channels);
              waveIn.StartRecording();
          }
      }
  
      void waveIn_DataAvailable(object sender, WaveInEventArgs e)
      {
          for (int index = 0; index &lt; e.BytesRecorded; index += 2)
          {
              short sample = (short)((e.Buffer[index + 1] &lt;&lt; 8) |
                                      e.Buffer[index + 0]);
              float sample32 = sample / 32768f;
              ProcessSample(sample32);
          }           
  
      }
  
      void ProcessSample(float sample1)
      {
          samplenumber += 1;
  
          if (sample1 &gt; maxval)
          {
              maxval = sample1;
          }
  
          if (sample1 &lt; minval)
          {
              minval = sample1;
          }
  
  
          //Run updateView every few loops
  
          if (samplenumber &gt; (double)SAMPLE_RATE / DISPLAY_UPDATE_RATE)
          {
              samplenumber = 0;
              updateView(); //needs to be fast!
          }
      }
  
      void updateView()
      {
          Console.WriteLine(maxval);
          Console.WriteLine(minval);
          progressBar1.Value = (maxval - minval)*50;
  
          maxval = 0;
          minval = 0;
      }
  </code></pre>