using UnityEngine;
using System.Collections;


public class MicInput : MonoBehaviour {

    public float sensitivity = 100;
    public float loudness = 0;
    public AudioSource audio;
    public float frequency = 0.0f;
    public int samplerate = 11024;

    private string input_Device;
    private GameObject inputCarrier;


    void Start () 
    {
        inputCarrier = GameObject.Find("LevelManager");
        input_Device = inputCarrier.GetComponent<LevelManager>().inputDevice;


        string[] mic=Microphone.devices;
        for(int i=0;i<mic.Length;++i)
        {
            //Debug.LogWarning(mic[i]);
        }
        audio.loop = true; // Set the AudioClip to loop
     //   audio.mute = true; // Mute the sound, we don't want the player to hear it

        if(mic.Length>0)
        {
            audio.clip = Microphone.Start(input_Device, true, 10, 44100);
            while (!(Microphone.GetPosition(mic[0]) > 0)) { } // Wait until the recording has started
           
        }
        else
        {
            audio.clip = Microphone.Start(null, true, 10, 44100);
            while (!(Microphone.GetPosition(null) > 0)) { } // Wait until the recording has started
        }
        audio.Play(); // Play the audio source!
	}
	
	void Update () 
    {
        loudness = GetAveragedVolume() * sensitivity;
        frequency = GetFundamentalFrequency();
	}

    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 / 256;
    }

    float GetFundamentalFrequency()
    {
        float fundamentalFrequency = 0.0f;
        float[] data = new float[8192];
        audio.GetSpectrumData(data, 0, FFTWindow.BlackmanHarris);
        float s = 0.0f;
        int i = 0;
        for (int j = 1; j < 8192; j++)
        {
            if (s < data[j])
            {
                s = data[j];
                i = j;
            }
        }
        fundamentalFrequency = i * samplerate / 8192;
        return fundamentalFrequency;
    }
}
