Created
March 25, 2019 12:37
-
-
Save yoshitaka-xvi/38ea7f902270ffc99d0b9ae950a3e5f1 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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class SimpleLoopback : MonoBehaviour { | |
public string[] DeviceNames = new string[2]; | |
public int prepareBufferSize = 1024; | |
AudioSource source; | |
AudioClip[] microphoneClips = new AudioClip[2]; | |
AudioClip playbackClip; | |
bool preparing = true; | |
float[][] microphoneBuffers = new float[2][]; | |
float[] playbackBuffer = new float[44100 * 2]; | |
void Start() { | |
for (var channel = 0; channel < microphoneClips.Length; channel++) { | |
microphoneClips[channel] = Microphone.Start(DeviceNames[channel], true, 1, 44100); | |
microphoneBuffers[channel] = new float[44100]; | |
} | |
playbackClip = AudioClip.Create("SimpleLoopback", 44100, 2, 44100, false); | |
source = GetComponent<AudioSource>(); | |
source.clip = playbackClip; | |
source.loop = true; | |
} | |
void Update() { | |
foreach (var device in DeviceNames) { | |
if (Microphone.GetPosition(device) < 0) { | |
return; | |
} | |
} | |
for (var channel = 0; channel < microphoneClips.Length; channel++) { | |
microphoneClips[channel].GetData(microphoneBuffers[channel], 0); | |
for (var sampleIndex = 0; sampleIndex < 44100; sampleIndex++) { | |
playbackBuffer[sampleIndex * 2 + channel] = microphoneBuffers[channel][sampleIndex]; | |
} | |
} | |
playbackClip.SetData(playbackBuffer, 0); | |
if (preparing) { | |
var prepared = true; | |
foreach (var device in DeviceNames) { | |
if (Microphone.GetPosition(device) < prepareBufferSize) { | |
prepared = false; | |
} | |
} | |
if (prepared) { | |
preparing = false; | |
source.Play(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment