How to make objects react to Music [Unity] | English

https://www.youtube.com/watch?v=LlkdQSjXd_A

創(chuàng)建一個AudioSource
利用audioSource.clip.GetData 拿到一個時間段的sample data,然后計算出一個大概的數(shù)值
https://docs.unity3d.com/ScriptReference/AudioClip.GetData.html

1024個sample 大概 = 80ms 八十毫秒

來自@xichen的圖片幫助解答
using UnityEngine;

public class AudioSourceLoudnessTester : MonoBehaviour
{
    public AudioSource audioSource;
    public float updateStep = 0.1f;
    public int sampleDataLength = 1024;

    private float currentUpdateTime = 0f;

    public float clipLoudness;
    private float[] clipSampleData;

    public GameObject cube;
    public float sizeFactor = 1;

    public float minSize = 0;
    public float maxSize = 500;

    // Use this for initialization
    private void Awake()
    {
        clipSampleData = new float[sampleDataLength];
    }

    // Update is called once per frame
    private void Update()
    {
        currentUpdateTime += Time.deltaTime;
        if (currentUpdateTime >= updateStep)
        {
            currentUpdateTime = 0f;
            audioSource.clip.GetData(clipSampleData, audioSource.timeSamples); //I read 1024 samples, which is about 80 ms on a 44khz stereo clip, beginning at the current sample position of the clip.
            clipLoudness = 0f;
            foreach (var sample in clipSampleData)
            {
                clipLoudness += Mathf.Abs(sample);
            }
            clipLoudness /= sampleDataLength; //clipLoudness is what you are looking for

            clipLoudness *= sizeFactor;
            clipLoudness = Mathf.Clamp(clipLoudness, minSize, maxSize);
            cube.transform.localScale = new Vector3(clipLoudness, clipLoudness, clipLoudness);
        }
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容