BinaryImpactG

UnityTip - Visualize an AudioFile

Apr 28th, 2020
465
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. // this is a shortend example for better readability
  5. public class UnityTip : MonoBehaviour {
  6.     public Material emissiveMaterial; // give it a material with an emission texture
  7.     public Color emissionColor;       // desired color
  8.  
  9.     private AudioSource _as;
  10.     private float currentUpdateTime = 0f;
  11.     // declared here to avoid GarbageCollection hickups
  12.     private float clipLoudness = 0f;
  13.     private float[] _clipSampleData;
  14.  
  15.     private void Start () {
  16.         _as = GetComponent<AudioSource> ();  // get audio source
  17.         _clipSampleData = new float[ 4410 ]; // initialize the sampleData array
  18.     }
  19.  
  20.     private void Update () {
  21.         if ( _as.isPlaying ) {
  22.             currentUpdateTime += Time.deltaTime;
  23.             if ( currentUpdateTime >= 0.1f ) {
  24.                 currentUpdateTime = 0f;
  25.  
  26.                 // fills the array /w samples; 4410 samples are 100 ms on a 44.1khz stereo clip
  27.                 // beginning at the current sample position of the clip
  28.                 _as.clip.GetData ( _clipSampleData, _as.timeSamples );
  29.                 clipLoudness = 0f;
  30.                 foreach ( var sample in _clipSampleData ) {
  31.                     clipLoudness += Mathf.Abs ( sample );
  32.                 }
  33.  
  34.                 // the samples are in the range -1 to 1
  35.                 // divide by 4410 to get an average and multiply by some factor to make it brighter
  36.                 float t = clipLoudness / 4410f * 18f;
  37.                 emissiveMaterial.SetColor ( "_EmissionColor", Color.Lerp ( Color.black, emissionColor, t ) );
  38.             }
  39.         }
  40.     }
  41. }
RAW Paste Data