Skip to content

Instantly share code, notes, and snippets.

@renaudbedard
Created September 25, 2014 03:37
Show Gist options
  • Save renaudbedard/b909a2cea8f6634cbc46 to your computer and use it in GitHub Desktop.
Save renaudbedard/b909a2cea8f6634cbc46 to your computer and use it in GitHub Desktop.
Waveform visualizer
using System;
using System.Collections;
using System.Threading;
using UnityEngine;
class WaveformDisplay : MonoBehaviour
{
public Tracker Tracker;
public int LineSegments;
[Range(0, 16384)]
public int SampleWindow;
static Material lineMaterial;
float[] buffer;
static void EnsureLineMaterial()
{
if (!lineMaterial)
{
lineMaterial = new Material("Shader \"Lines/Colored Blended\" {" +
"SubShader { Pass { " +
" Blend SrcAlpha OneMinusSrcAlpha " +
" ZWrite Off Cull Off Fog { Mode Off } " +
" BindChannels {" +
" Bind \"vertex\", vertex Bind \"color\", color }" +
"} } }");
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
}
}
void OnGUI()
{
if (buffer == null || buffer.Length != SampleWindow)
buffer = new float[SampleWindow];
Tracker.audio.GetOutputData(buffer, 0);
EnsureLineMaterial();
lineMaterial.SetPass(0);
GL.Begin(GL.LINES);
GL.Color(new Color(1, 1, 1, 1));
float screenOffset = transform.position.x;
float width = transform.localScale.x;
float height = transform.localScale.y;
for (int i = 0; i < LineSegments; i++)
{
int fromSample = Mathf.RoundToInt((float)i / LineSegments * SampleWindow);
int toSample = Mathf.RoundToInt((float)(i + 1) / LineSegments * SampleWindow);
float fromValue = buffer[Mathf.Clamp(fromSample, 0, buffer.Length - 1)];
float toValue = buffer[Mathf.Clamp(toSample, 0, buffer.Length - 1)];
GL.Vertex3(((float)i / LineSegments) * width + screenOffset, fromValue * height, 0);
GL.Vertex3(((float)(i + 1) / LineSegments) * width + screenOffset, toValue * height, 0);
}
GL.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment