How would I edit the height of say a cube in real time that is relative to the audio levels?
You can get the audio level in dB or in RMS (root mean square) using the script below, then change the Y scale based on the value returned. RMS values are easier to use, since they range from 0 to 1. dB values are more complicated, because they are calculated by 20*Log10(rmsValue/refValue): thus, the value returned may be positive (sound > ref level) or negative (sound < ref level). Negative dB values are clamped to -160, but positive values have no limit. There’s a more complete version of this script in [this][1] answer - the dominant pitch of the sound is returned too.
The object to which the script below is attached must also have the audio source, and will vary its vertical scale according to the RMS value:
var qSamples: int = 1024; // array size
var refValue: float = 0.1; // RMS value for 0 dB
var rmsValue: float; // sound level - RMS
var dbValue: float; // sound level - dB
var volume: float = 2; // set how much the scale will vary
private var samples: float[]; // audio samples
function Start () {
samples = new float[qSamples];
}
function GetVolume(){
audio.GetOutputData(samples, 0); // fill array with samples
var i: int;
var sum: float = 0;
for (i=0; i < qSamples; i++){
sum += samples_*samples*; // sum squared samples*_
* }*
* rmsValue = Mathf.Sqrt(sum/qSamples); // rms = square root of average*
_ dbValue = 20Mathf.Log10(rmsValue/refValue); // calculate dB_
_ if (dbValue < -160) dbValue = -160; // clamp it to -160dB min*_
}
function Update () {
* GetVolume();*
_ transform.localScale.y = volume * rmsValue;_
}
_*[1]: http://answers.unity3d.com/questions/157940/getoutputdata-and-getspectrumdata-they-represent-t.html?viewedQuestions=165729&viewedQuestions=165699&viewedQuestions=165576&viewedQuestions=165546&viewedQuestions=157940&viewedQuestions=165673*_