Created
March 25, 2019 11:48
-
-
Save yoshitaka-xvi/1b18ccfa816d90e513362505939b1c14 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; | |
using System; | |
[RequireComponent(typeof(AudioSource))] | |
public class LoopbackMicrophone : MonoBehaviour { | |
public int prepareBufferSize = 1024; | |
AudioClip clip; | |
AudioClip playbackClip; | |
AudioSource source; | |
bool preparing = true; | |
int head = 0; | |
const int samplingFrequency = 44100; | |
const int lengthSeconds = 1; | |
float[] processBuffer = new float[256]; | |
float[] microphoneBuffer = new float[lengthSeconds * samplingFrequency]; | |
void Start() { | |
clip = Microphone.Start(null, true, lengthSeconds, samplingFrequency); | |
playbackClip = AudioClip.Create("LoopbackMicrophone", lengthSeconds * samplingFrequency, 1, samplingFrequency, false); | |
source = GetComponent<AudioSource>(); | |
source.clip = playbackClip; | |
source.loop = true; | |
} | |
void Update() { | |
var position = Microphone.GetPosition(null); | |
if (position < 0 || head == position) { | |
return; | |
} | |
clip.GetData(microphoneBuffer, 0); | |
playbackClip.SetData(microphoneBuffer, 0); | |
if (preparing && position >= prepareBufferSize) { | |
preparing = false; | |
source.Play(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment