Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- // this is a shortend example for better readability
- public class UnityTip : MonoBehaviour {
- public Material emissiveMaterial; // give it a material with an emission texture
- public Color emissionColor; // desired color
- private AudioSource _as;
- private float currentUpdateTime = 0f;
- // declared here to avoid GarbageCollection hickups
- private float clipLoudness = 0f;
- private float[] _clipSampleData;
- private void Start () {
- _as = GetComponent<AudioSource> (); // get audio source
- _clipSampleData = new float[ 4410 ]; // initialize the sampleData array
- }
- private void Update () {
- if ( _as.isPlaying ) {
- currentUpdateTime += Time.deltaTime;
- if ( currentUpdateTime >= 0.1f ) {
- currentUpdateTime = 0f;
- // fills the array /w samples; 4410 samples are 100 ms on a 44.1khz stereo clip
- // beginning at the current sample position of the clip
- _as.clip.GetData ( _clipSampleData, _as.timeSamples );
- clipLoudness = 0f;
- foreach ( var sample in _clipSampleData ) {
- clipLoudness += Mathf.Abs ( sample );
- }
- // the samples are in the range -1 to 1
- // divide by 4410 to get an average and multiply by some factor to make it brighter
- float t = clipLoudness / 4410f * 18f;
- emissiveMaterial.SetColor ( "_EmissionColor", Color.Lerp ( Color.black, emissionColor, t ) );
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement