using UnityEngine;
using System.Collections;

	[RequireComponent(typeof(AudioSource))]

	public class MicrophoneInput : MonoBehaviour {
	public AudioSource audioSource;

    public float sensitivity = 0.5f;
	public float loudness = 0.0f;
	public float frequency = 0.0f;
	public float samplerate = 11024;


    void Start() {
		audioSource = GetComponent<AudioSource> ();
        foreach (string audioDevice in Microphone.devices)
        {
            
            Debug.Log(audioDevice);

  
        }

        if (tag == "Player1")
            StartRecording(0);


        if (tag == "Player2")
            StartRecording(1);



    }

    void Update(){
		loudness = GetAveragedVolume () * sensitivity;
		frequency = GetFundamentalFrequency ();
		//Debug.Log (loudness);
	}	


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

	public float GetFundamentalFrequency()
	{
		float fundamentalFrequency = 0.0f;
		float[] data = new float[8192];
		audioSource.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;
	}

    void StartRecording(int micNr)
    {
        if (Microphone.devices[micNr] == null)
        {
            Debug.LogError("No Recording!");
        }

        audioSource.clip = Microphone.Start(Microphone.devices[micNr], true, 10, 44100);
       
        audioSource.loop = true;
        while (!(Microphone.GetPosition(Microphone.devices[micNr]) > 0)) { }
        audioSource.Play(); 

        



       
    }

}
