using UnityEngine;

using System;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class MicrophoneInput : MonoBehaviour 
{
    // PARAMETERS

    public float Sensitivity = 100.0f;

    // INTERNALS

    private float _Loudness = 0.0f;

    public float Loudness
    {
        get { return _Loudness; }
    }

    public float NormalizedLoudness
    {
        get
        {
            if (Sensitivity != 0.0f)
            {
                return _Loudness / Sensitivity;
            }

            return 0.0f;
        }
    }

    void Start()
    {
        audio.clip = Microphone.Start(null, true, 10, 44100);
        audio.loop = true;
        audio.mute = true;

        while (!(Microphone.GetPosition("AudioInputDevice") > 0))
        {
            // Do nothing.
        }

        audio.Play();
    }

    void Update()
    {
        _Loudness = Sensitivity * GetAveragedVolume();
    }

    float GetAveragedVolume()
    {
        float[] data = new float[256];
        float a = 0;
        
        audio.GetOutputData(data, 0);
        
        foreach (float s in data)
        {
            a += Mathf.Abs(s);
        }
        
        return a / 256f;
    }
}
