- Home /
Question by
mate_veres · May 19, 2020 at 10:54 PM ·
audioaudiosourceaudioclipaudiolistenernoise
Noise cancelling
HI, I tried out noise cancelling today. My code is working by getting the samples of a clip, then multiplying the values by -1 and playing the new clip with the other and sometimes it worked the two listeners together were quieter together, than when only one was playing. However, these were the rarer occasions. Sometimes there weren't changing anything when I muted one or even worse the two together sounded like they are not playing at once. Can someone explain me the reason behind this inconsistency? Here is my code: (the part at the end is only for testing whether they should cancel each other out)
using UnityEngine; using System.Collections;
[RequireComponent(typeof(AudioSource))] public class NoiseCancelling : MonoBehaviour {
public AudioSource original;
public AudioSource cancelled;
AudioClip clip;
AudioClip newclip;
float[] samples;
private void Start()
{
for (int i = 0; i < Microphone.devices.Length; i++)
{
Debug.Log(Microphone.devices[i]);
}
original.Play();
clip = original.clip;
newclip = original.clip;
samples = new float[clip.samples * clip.channels];
clip.GetData(samples, 0);
for (int i = 0; i < samples.Length; i++)
{
samples[i] = samples[i] * -1f;
}
newclip.SetData(samples, 0);
cancelled.clip = newclip;
original.Play();
cancelled.Play();
float[] testsample1 = new float[cancelled.clip.samples * cancelled.clip.channels];
float[] testsample2 = new float[original.clip.samples * original.clip.channels];
float[] zeros = new float[testsample1.Length];
for (int i = 0; i < testsample1.Length; i++)
{
zeros[i] = testsample1[i] + testsample2[i];
}
Debug.Log(Mathf.Max(zeros));
}
Comment