Skip to content

Instantly share code, notes, and snippets.

@JoeCooper
Last active July 7, 2021 05:30
Show Gist options
  • Select an option

  • Save JoeCooper/4cf53c268ad5aad53f5dd0c425db666b to your computer and use it in GitHub Desktop.

Select an option

Save JoeCooper/4cf53c268ad5aad53f5dd0c425db666b to your computer and use it in GitHub Desktop.
Code for a Unity3D component. Attach to a GameObject. AudioSource will generate automatically; make sure it is 2D. With "negation mode" to "negate one", if speakers are next to each other, they should jam each others' signal, mimicking an active noise cancellation system.
using UnityEngine;
[RequireComponent(typeof(AudioSource))]
public class NoiseCancellationExperiment : MonoBehaviour {
public enum Mode {
Direct, NegateOne, NegateBoth
}
public int samplesPerSecond = 44100;
public double[] tones = new [] { 350.0, 440.0 };
public Mode negationMode;
const int channels = 2;
int offset;
// Use this for initialization
void Awake () {
var audioSource = GetComponent<AudioSource>();
audioSource.loop = true;
audioSource.clip = AudioClip.Create("Tone", samplesPerSecond, channels, samplesPerSecond / channels, true, Produce);
audioSource.Play();
}
void Produce(float[] samples) {
double factor = 2.0 / (double) samplesPerSecond;
for(var i = 0; i < samples.Length; ) {
double builder = 0.0;
for(int j = 0; j < tones.Length; j++) {
builder = builder + System.Math.Sin((double) (offset + i) * factor * tones[j] * System.Math.PI);
}
double alfa, bravo;
alfa = bravo = builder / (double) tones.Length;
if(negationMode == Mode.NegateOne) {
bravo = -bravo;
} else if(negationMode == Mode.NegateBoth) {
alfa = -alfa;
bravo = -bravo;
}
samples[i++] = (float) alfa;
samples[i++] = (float) bravo;
}
offset += samples.Length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment