How to do it...

To use sound waveforms for animation, follow these steps:

  1. Import the sound into Unity.
  2. Create an empty game object and name it AudioSource.
  3. Add an Audio Source component to it, and make the sound Loop and Play On Awake. Drag and drop your sound into the AudioClip field.
  4. Create a Cube game object (go to Game Object3D ObjectCube).
  5. Create a new script and call it ScaleWithWaveForm.cs. In this script, we have one public AudioSource audioSource variable, one public float lerpSpeed variable, one  float[] samples array, and a float currentSample variable to store the average volume of the samples. In this script's Start() function, we set the size of the samples array to 1024 (it needs to be a power of 2). This is the number of samples we will read from the Audio Source. We also start a IEnumerator SampleAudio() coroutine:
        public AudioSource audioSource; 
        public float lerpSpeed = 100f; 
        float[] samples; 
        float currentSample; 
 
        void Start() 
        { 
            samples = new float[1024]; 
            StartCoroutine("SampleAudio"); 
        } 
  1. This coroutine uses the audioSource.GetOutputData() function to get and store the output audio samples in the samples array. Then we sum all the squared samples and calculate an average volume (the RMS). Lastly, we use this value to scale the Cube game object. Additionally, we interpolate the scale changes in time to make it smoother. The currentSample value is multiplied by 10 to make the changes more visible (RMS ranges from 0 to 1):
        IEnumerator SampleAudio() 
        { 
            while (true) 
            { 
                audioSource.GetOutputData(samples, 0); 
                currentSample = 0f; 
                for (int i = 0; i < samples.Length; i++) 
                { 
                    currentSample += (samples[i]* 
                    samples[i]); 
                } 
                currentSample = Mathf.Sqrt(currentSample / 
                samples.Length); 
         
                transform.localScale = 
                Vector3.Lerp(transform.localScale, 
                Vector3.one * currentSample*100f, 
                Time.deltaTime*4f); 
         
                yield return null; 
            } 
       } 
  1. Assign the script to the Cube game object.
  2. Drag and drop the AudioSource game object into the Audio Source field of the script.
  3. Play the game to see the effect.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.186.109