Unity3d:应该在哪个类中调用音频处理或计算?

时间:2015-12-17 07:27:10

标签: c# audio unity3d unityscript

我正在创建一个使用Unity5游戏引擎对振幅做出反应的视听器。我使用对数,RMS值和.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);
    /***/
}

2 个答案:

答案 0 :(得分:0)

您希望在渲染之前立即重新缩放立方体,以便在“测量”振幅和显示结果之间获得最小的延迟。从Unity手册中查看this page,页面下方是一个流程图,解释了在MonoBehavi上调用每个函数的时间。如您所见,OnPreRender()是在渲染场景之前调用的最后一个函数,因此我会尝试将代码放在那里。如果这不起作用,请在此之前尝试该功能,依此类推。

答案 1 :(得分:0)

执行计算或可视化代码的每帧方法无关紧要。 你可以使用从Update到LateUpdate,OnPreRender,OnPostRender的任何内容,因为它们都被称为每一帧,几乎没有可测量的时差。

如果您的可视化似乎落后于当前正在播放的音频输出,则有几种可能性:

  1. 你错了,可视化实际上是正确的
  2. 可视化是错误的,你不小心反映它或类似的东西
  3. 可视化是正确的,但可视化的数据计算错误
  4. 数据,计算和可视化是正确的,但使用GetOutputData获取的数据已过时。
  5. 您的帧率非常低(~5 fps),当前正在播放的音频与可视化结果之间确实存在明显的时差。如果你每帧使用它,Debug.Log()非常慢(!!)。