-
-
Save martindevans/88fa9f308ea89976462b9d5f4c38c5c4 to your computer and use it in GitHub Desktop.
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 Dissonance; | |
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using NAudio; | |
using NAudio.Wave; | |
using System.Linq; | |
using UnityEngine.UIElements; | |
public class Echo : MonoBehaviour | |
{ | |
public const int samplerate = 48000; | |
DissonanceComms DC; | |
AudioSource audiosrc; | |
MyMicrophoneSubscriber MS; | |
// Start is called before the first frame update | |
void Start() | |
{ | |
MS = gameObject.AddComponent<MyMicrophoneSubscriber>(); | |
DC = GameObject.Find("DissonanceComms").GetComponent<DissonanceComms>(); | |
audiosrc = gameObject.AddComponent<AudioSource>(); | |
DC.SubscribeToRecordedAudio(MS); | |
StartCoroutine(WaitRemoteClip()); | |
} | |
IEnumerator WaitRemoteClip() | |
{ | |
while (true) | |
{ | |
yield return new WaitForSeconds(1.5f); | |
var audioclip = AudioClip.Create("MySinusoid", 4096, 1, samplerate, true, MS.OnAudioRead, MS.OnAudioSetPosition); | |
audiosrc.clip = audioclip; | |
audiosrc.PlayOneShot(audioclip); | |
} | |
} | |
} | |
public class MyMicrophoneSubscriber | |
: BaseMicrophoneSubscriber | |
{ | |
readonly List<float> bufferlist = new List<float>(); | |
private int position; | |
protected override void ProcessAudio(ArraySegment<float> data) | |
{ | |
bufferlist.AddRange(data); | |
} | |
protected override void ResetAudioStream(WaveFormat waveFormat) | |
{ | |
if (waveFormat.SampleRate != Echo.samplerate) | |
throw new NotImplementedException("Wrong sample rate"); | |
Debug.Log("Reset"); | |
bufferlist.Clear(); | |
} | |
//After you have copied some amount of data from the bufferlist into the data array, | |
// you need to remove exactly that much data from the start of the buffer. | |
public void OnAudioRead(float[] data) | |
{ | |
if (bufferlist.Count < data.Length) | |
{ | |
Debug.LogWarning($"Underrun {bufferlist.Count} < {data.Length}"); | |
// Return silence for now | |
Array.Clear(data, 0, data.Length); | |
// Pad out buffer with some extra silence, to add more delay | |
for (var i = 0; i < 480; i++) | |
bufferlist.Add(0); | |
return; | |
} | |
bufferlist.CopyTo(0, data, 0, data.Length); | |
bufferlist.RemoveRange(0, data.Length); | |
} | |
public void OnAudioSetPosition(int newPosition) | |
{ | |
Debug.Log($"Set Position: {newPosition}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment