美文网首页Unity x Sound
How to make objects react to Mus

How to make objects react to Mus

作者: zitaoye | 来源:发表于2021-01-27 16:46 被阅读0次

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

    创建一个AudioSource
    利用audioSource.clip.GetData 拿到一个时间段的sample data,然后计算出一个大概的数值
    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);
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:How to make objects react to Mus

        本文链接:https://www.haomeiwen.com/subject/mwongktx.html