Skip to content

Instantly share code, notes, and snippets.

@MirzaBeig
Created August 15, 2024 03:52
Show Gist options
  • Save MirzaBeig/639fe29d075703287fb82b37e2ad6c2f to your computer and use it in GitHub Desktop.
Save MirzaBeig/639fe29d075703287fb82b37e2ad6c2f to your computer and use it in GitHub Desktop.
A simple procedural audio (pure sine wave) generator for Unity, using OnAudioFilterRead().
using UnityEngine;
// MB: Simple procedural audio generator.
// Generates a pure sine wave/tone at a given frequency.
public class SimpleAudioGenerator : MonoBehaviour
{
int outputSampleRate;
const float TAU = Mathf.PI * 2.0f;
// Continous phase = continuous tone.
float phase = 0.0f;
// Careful, this can be very loud!
[Range(0.0f, 1.0f)]
public float amplitude = 0.5f;
// ~Typical range of human hearing is 20Hz to 20kHz.
[Range(100.0f, 8000.0f)]
public float frequency = 440.0f; // A4.
float phaseStep;
void Start()
{
outputSampleRate = AudioSettings.outputSampleRate;
}
void Update()
{
phaseStep = (frequency * TAU) / outputSampleRate;
}
void OnAudioFilterRead(float[] data, int channels)
{
for (int i = 0; i < data.Length; i += channels)
{
float sample = Mathf.Sin(phase) * amplitude;
for (int j = 0; j < channels; j++)
{
data[i + j] = sample;
}
phase += phaseStep;
// Phase = [0.0f, TAU).
if (phase > TAU)
{
phase -= TAU;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment