How do I access properties of audio to affect the game?

For example:

  • An orb that speaks, and grows and shrinks as its voice (audio source) gets louder and softer
  • A Robot who has lights on its mouth that glow as it speaks
  • A music game where the objects themselves move and pulsate along with the volume or pitch of the song

I’ve tried the component audio.volume, but that just accesses the user-set volume component. How do I access the properties of what the audio clip is currently playing?

Take a look at this question: my answer shows a script that modifies the object’s Y scale according to the volume of the sound it’s playing.

I found this pretty nice tutorial
How to Use Sound to Make 3D Geometry in Unity

I used aldonaletto’s script, but I ended up chaning it to C#, and changing the parent’s size instead, Ill post my script here, hope it helps someone!

using UnityEngine;
using System.Collections;

public class SizeFromVolume : MonoBehaviour
{

    public int qSamples = 1024;
    public float refValue = 0.1f;
    public float rmsValue;
    public float dbValue;
    public float Volume = 2;

    float[] samples;

    // Use this for initialization
    void Start()
    {
        samples = new float[qSamples];
    }

    void GetVolume()
    {
        


        GetComponent<AudioSource>().GetOutputData(samples, 0); // fill array with samples
        int i;
        float sum = 0f;
        for (i = 0; i < qSamples; i++)
        {
            sum += samples _* samples*; // sum squared samples*_

}
rmsValue = Mathf.Sqrt(sum / qSamples); // rms = square root of average
dbValue = 20 * Mathf.Log10(rmsValue / refValue); // calculate dB
if (dbValue < -160) dbValue = -160; // clamp it to -160dB min
}

// Update is called once per frame
void Update()
{
GetVolume();
Vector3 scale = transform.parent.gameObject.transform.localScale;
transform.parent.gameObject.transform.localScale = new Vector3(scale.x, Volume * rmsValue, scale.z);
}
}

Thanks aldonaletto!