using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AmplitudeAnimator : MonoBehaviour {
    public AudioSource audiosource;
    Animator anim;
    float minVal = float.MaxValue;
    float maxVal = float.MinValue;
	// Use this for initialization
	void Awake () {
        anim = GetComponent<Animator>();
	}
	
	// Update is called once per frame
	void Update () {
        float val = GetRMS(0) * 3.1f;
        if (val < minVal) minVal = val;
        if (val > maxVal) maxVal = val;
        anim.SetFloat("Blend", Mathf.Clamp(val,0f,1f));
        //print("min val is: " + minVal + ", max val is: " + maxVal);
    }

    
    float GetRMS(int channel) {
        int s = 4096;
        float[] samples = new float[s];
        audiosource.GetOutputData(samples, channel); // fill array with samples var sum: float = 0;
        float sum = 0;
        for (var i=0; i < s; i++) {
            sum += samples[i]*samples[i]; // sum squared samples 
        }
        return Mathf.Sqrt(sum/s); // rms = square root of average 
    }
}
