title: Unity3d: Check Microphone Input Volume
body: <p>I want to use the volume of the audio that the user inputs with his/her microphone in Unity3d in a visual representation. So I'd like to get a value between 0 and 1 that tell how loud the user is. I went looking for a script, but the part that handles the volume doesn't work properly, that part is the method <code>LevelMax()</code>. For some reason <code>micPosiotion</code> never becomes higher than 0. I don't know what <code>Microphone.GetPosition</code> really does except for this: </p>
  
  <p><a href="http://docs.unity3d.com/ScriptReference/Microphone.GetPosition.html" rel="nofollow">http://docs.unity3d.com/ScriptReference/Microphone.GetPosition.html</a></p>
  
  <p>Does anyone know what goes wrong in the method <code>LevelMax()</code>? I am getting no errors or anything. And it finds my microphone properly, and it is working. I tested it.</p>
  
  <p>This is the code:</p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  
  public class MicInput : MonoBehaviour{
  
      public float testSound;
      public static float MicLoudness;
      private string _device;
      private AudioClip _clipRecord = new AudioClip();
      private int _sampleWindow = 128;
      private bool _isInitialized;
  
      void InitMic()
      {
          if (_device == null) {
              _device = Microphone.devices [0];
              _clipRecord = Microphone.Start (_device, true, 999, 44100);
              Debug.Log (_clipRecord);
          }
      }
  
      void StopMicrophone()
      {
          Microphone.End (_device);
      }
  
      float LevelMax()
      {
          float levelMax = 0;
          float[] waveData = new float[_sampleWindow];
          int micPosition = Microphone.GetPosition (null) - (_sampleWindow + 1);
          if (micPosition &lt; 0) {
              return 0;
          }
          _clipRecord.GetData (waveData, micPosition);
          for (int i = 0; i &lt; _sampleWindow; ++i) {
              float wavePeak = waveData [i] * waveData [i];
              if (levelMax &lt; wavePeak) {
                  levelMax = wavePeak;
              }
          }
          return levelMax;
      }
  
      void Update()
      {
          MicLoudness = LevelMax ();
          testSound = MicLoudness;
  
      }
  
      void OnEnable()
      {
          InitMic ();
          _isInitialized = true;
      }
  
      void OnDisable()
      {
          StopMicrophone ();
      }
  
      void OnDestory()
      {
          StopMicrophone ();
      }
  
      void OnApplicationFocus(bool focus)
      {
          if (focus) {
              if (!_isInitialized) {
                  InitMic ();
                  _isInitialized = true;
              }
          }
  
          if (!focus) {
              StopMicrophone ();
              _isInitialized = false;
          }
      }
  
  }
  </code></pre>