Skip to content

Instantly share code, notes, and snippets.

@robksawyer
Created May 11, 2015 05:33
Show Gist options
  • Select an option

  • Save robksawyer/47196d488441cb0de906 to your computer and use it in GitHub Desktop.

Select an option

Save robksawyer/47196d488441cb0de906 to your computer and use it in GitHub Desktop.
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