Created
May 11, 2015 05:33
-
-
Save robksawyer/47196d488441cb0de906 to your computer and use it in GitHub Desktop.
Found via a Unity answer and thought it was interesting. http://answers.unity3d.com/questions/897466/is-it-possible-to-render-spectrum-data-onto-a-ui-i.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using UnityEngine.UI; | |
| using System.Collections; | |
| //[RequireComponent(typeof(AudioSource))] | |
| [RequireComponent(typeof(GUITexture))] | |
| public class AudioWaveFormVisualizer : MonoBehaviour | |
| { | |
| public AudioSource MusicPlayer; | |
| public int width = 500; // texture width | |
| public int height = 100; // texture height | |
| public Color backgroundColor = Color.black; | |
| public Color waveformColor = Color.green; | |
| public int size = 2048; // size of sound segment displayed in texture | |
| private Color[] blank; // blank image array | |
| private Texture2D texture; | |
| private float[] samples; // audio samples array | |
| IEnumerator Start () | |
| { | |
| // create the samples array | |
| samples = new float[size]; | |
| // create the texture and assign to the guiTexture: | |
| texture = new Texture2D (width, height); | |
| guiTexture.texture = texture; | |
| // create a 'blank screen' image | |
| blank = new Color[width * height]; | |
| for (int i = 0; i < blank.Length; i++) { | |
| blank [i] = backgroundColor; | |
| } | |
| // refresh the display each 100mS | |
| while (true) { | |
| GetCurWave (); | |
| yield return new WaitForSeconds (0.1f); | |
| } | |
| } | |
| void GetCurWave () | |
| { | |
| // clear the texture | |
| texture.SetPixels (blank, 0); | |
| // get samples from channel 0 (left) | |
| MusicPlayer.GetOutputData (samples, 0); | |
| // draw the waveform | |
| for (int i = 0; i < size; i++) { | |
| texture.SetPixel ((int)(width * i / size), (int)(height * (samples [i] + 1f) / 2f), waveformColor); | |
| } // upload to the graphics card | |
| texture.Apply (); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment