Created
November 9, 2012 15:43
-
-
Save boj/4046399 to your computer and use it in GitHub Desktop.
Oscillator Experiment
This file contains 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 System; | |
using System.Diagnostics; | |
using System.Threading; | |
// http://www.codeproject.com/Articles/30180/Simple-Signal-Generator | |
// http://blogs.msdn.com/b/dawate/archive/2009/06/25/intro-to-audio-programming-part-4-algorithms-for-different-sound-waves-in-c.aspx | |
class Oscilator : MonoBehaviour { | |
public enum Type { SINE, SQUARE, TRIANGLE, SAWTOOTH }; | |
public float amplitude = 1.0f; | |
public float frequency = 1.0f; | |
public float phase = 0.0f; | |
public float offset = 0.0f; | |
public int invert = 1; // 1, -1 | |
public Type type = Type.SINE; | |
private long startTime = Stopwatch.GetTimestamp(); | |
private long ticksPerSecond = Stopwatch.Frequency; | |
private float GetTime() { | |
return (float)(Stopwatch.GetTimestamp() - startTime) / ticksPerSecond; | |
} | |
public void Reset() { | |
startTime = Stopwatch.GetTimestamp(); | |
} | |
void OnAudioFilterRead(float[] data, int channels) { | |
for (int i = 0; i < data.Length; i = i + channels) { | |
float value = 0f; | |
float t = frequency * GetTime() + phase; | |
switch (type) { | |
case Type.SINE: | |
value = (float)Math.Sin(2f * Math.PI * t); | |
break; | |
case Type.SQUARE: | |
value = Math.Sign(Math.Sin(2f * Math.PI * t)); | |
break; | |
case Type.TRIANGLE: | |
value = 1f - 4f * (float)Math.Abs(Math.Round(t - 0.25f) - (t - 0.25f)); | |
break; | |
case Type.SAWTOOTH: | |
value = 2f * (t - (float)Math.Floor(t + 0.5f)); | |
break; | |
} | |
data[i] = (invert * amplitude * value + offset); | |
if (channels == 2) data[i + 1] = data[i]; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment