Skip to content

Instantly share code, notes, and snippets.

@martindevans
Created August 3, 2020 15:30
Show Gist options
  • Save martindevans/3a09b4a31d864340685b812cf2e52bb3 to your computer and use it in GitHub Desktop.
Save martindevans/3a09b4a31d864340685b812cf2e52bb3 to your computer and use it in GitHub Desktop.
using System.Collections;
using UnityEngine;
namespace Assets
{
public class TestMic
: MonoBehaviour
{
// Set an explicit input device here. leave as null to use the default.
public string MicName = null;
private AudioClip _clip;
private AudioSource _source;
private void Start()
{
//Get device capabilities and choose a sample rate as close to 48000 as possible.
//If min and max are both zero that indicates we can use any sample rate
Microphone.GetDeviceCaps(MicName, out var minFreq, out var maxFreq);
var sampleRate = minFreq == 0 && maxFreq == 0 ? 48000 : Mathf.Clamp(48000, minFreq, maxFreq);
Debug.Log($"GetDeviceCaps name=`{MicName}` min=`{minFreq}` max=`{maxFreq}`");
// Start capturing audio from mic
_clip = Microphone.Start(MicName, true, 10, sampleRate);
if (_clip == null)
{
Debug.LogError("Failed to start microphone capture");
return;
}
StartCoroutine(WaitForMicClip());
}
private IEnumerator WaitForMicClip()
{
// Wait for recording to start
var count = 0;
while (Microphone.GetPosition(MicName) <= 0)
{
if (count % 10 == 0)
Debug.Log($"Waiting for recording to start ({count})");
count++;
yield return null;
}
_source = GetComponent<AudioSource>();
_source.loop = true;
_source.clip = _clip;
_source.Play();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment