Skip to content

Instantly share code, notes, and snippets.

@soyliquid
Last active August 29, 2015 14:14
Show Gist options
  • Save soyliquid/c0fee0555d9759a852ea to your computer and use it in GitHub Desktop.
Save soyliquid/c0fee0555d9759a852ea to your computer and use it in GitHub Desktop.
音の波形を画面に描画するスクリプト
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Camera))]
public class WaveVisualizer : MonoBehaviour {
public int dataLength = 128;
public float waveHeightWeight = 0.1f;
[Range(0f, 1f)]
public float waveWidth = 0.8f;
[Range(0f, 1f)]
public float baseX = 0.1f;
[Range(0f, 1f)]
public float baseY = 0.4f;
public float drawDepth = 10f;
public Material lineMaterial;
[Header("If size 0, automatically use AudioListener.")]
public AudioSource[] sources;
private Camera camera;
private float[] data;
void Awake() {
camera = GetComponent<Camera>();
}
void Update() {
data = new float[dataLength];
if (sources.Length == 0) {
AudioListener.GetOutputData(data, 0);
} else {
float[] buffer = new float[dataLength];
foreach (AudioSource audio in sources) {
audio.GetOutputData(buffer, 0);
for (int idx = 0; idx < dataLength; idx++) {
data[idx] += buffer[idx] / sources.Length;
}
}
}
}
void OnPostRender() {
lineMaterial.SetPass(0);
GL.Begin(GL.LINES);
GL.Color(Color.white);
float step = waveWidth / data.Length;
for (int idx = 0; idx < data.Length - 1; idx++) {
Vector3 v1 = camera.ViewportToWorldPoint(
new Vector3(
baseX + step * idx,
baseY + data[idx] * waveHeightWeight,
drawDepth));
Vector3 v2 = camera.ViewportToWorldPoint(
new Vector3(
baseX + step * (idx + 1),
baseY + data[idx + 1] * waveHeightWeight,
drawDepth));
GL.Vertex3(v1.x, v1.y, v1.z);
GL.Vertex3(v2.x, v2.y, v2.z);
}
GL.End();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment