我正在创建一个音频可视化工具,它使用Unity5游戏引擎对振幅做出反应。我使用对数、均方根值和.GetOutputData来计算振幅。
最初,我从Update类调用了我的函数,但它的反应时间太慢,可视化工具似乎与音乐不同步。我现在从OnGUI类调用我的函数,但它仍然不是对音乐的实时反应。
我应该在什么时候或如何调用我的函数来获得实时最佳的音频可视化效果?有没有更好的方法来做这件事?
谢谢你的帮助。
我的可视化函数:
void OnGUI ()
{
//PROCESS AMPLITUDE:
/***/
///RETRIEVE THE AUDIO-SOURCE SAMPLES:
//Declare and Initialize an array to store the samples;
float[] samples = new float[iSamples];
//Pass the samples' array to the audio-source;
auTheCurrentSong.GetOutputData (samples, 0);
///CALCULATE THE RMS VOLTAGE VALUE:
//Declare and Initialize the sum of the squared samples;
float fTotalSquaredSamples = 0.0f;
//FOR each sample in the samples' array...
for (int counter=0; counter < iSamples; counter++) {
//... Calculate the sum of the squared samples;
fTotalSquaredSamples += Mathf.Pow (samples [counter], 2);
}
//Calculate the average or mean of the total squared samples;
float fMeanSquaredSamples = fTotalSquaredSamples/iSamples;
//Calc ulate the root mean square (RMS) value;
float fRMS = Mathf.Sqrt (fMeanSquaredSamples);
//CALCULATE THE DECIBEL VALUE FOR OUTPUT:
//Calculate the decibel value;
float fdBValue = 20*Mathf.Log10(fRMS/fReference);
//Clamp dB values:
//IF dB values are less than -160...
if (fdBValue < -160)
{
//...Clamp dB values to -160;
fdBValue = -160;
}
//RESPOND TO PRODUCT:
//Debug the decibel values to check for irregularities;
Debug.Log (fdBValue);
//Scale a 3-D cube vertically depending on the dB value;
transform.localScale = new Vector3 (1.0f, fdBValue, 0.0f);
/***/
}发布于 2015-12-23 21:18:38
您可能希望在渲染立方体之前对其进行重新缩放,以便在“测量”振幅和显示结果之间具有尽可能小的延迟。看看Unity Manual中的this page,下一页是一个流程图,解释了在MonoBehaviour上调用每个函数的时间。正如您所看到的,OnPreRender()是在渲染场景之前调用的最后一个函数,因此我将尝试将您的代码放在那里。如果这不起作用,请在此之前尝试该函数,以此类推。
发布于 2015-12-24 01:20:25
执行计算或可视化代码的每帧方法实际上并不重要。你可以使用任何东西,从更新到LateUpdate,OnPreRender,OnPostRender,因为它们都被称为每一帧,几乎没有可测量的时间差。
如果您的可视化效果似乎落后于当前播放的音频输出,则有几种可能:
calculated
https://stackoverflow.com/questions/34328903
复制相似问题