Skip to content

Instantly share code, notes, and snippets.

@yadurajiv
Created January 17, 2019 05:46
Show Gist options
  • Save yadurajiv/bfbcbb3fdc6854af669afb2240f7001e to your computer and use it in GitHub Desktop.
Save yadurajiv/bfbcbb3fdc6854af669afb2240f7001e to your computer and use it in GitHub Desktop.
GetAudioData from microphone and calculate pitch
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
[RequireComponent(typeof(AudioSource))]
public class GetAudioData : MonoBehaviour {
AudioSource _audioSource;
// remember to create an audio mixer, create a subgroup on the master, set the new groups volume to -80 and attach it here!
public AudioMixerGroup _audioMixerMic;
public float rmsVal;
public float dbVal;
public float pitchVal;
private const int QSamples = 1024;
private const float RefValue = 0.1f;
private const float Threshold = 0.02f;
float[] _samples;
private float[] _spectrum;
private float _fSample;
bool isReady;
// Use this for initialization
void Start () {
isReady = false;
_samples = new float[QSamples];
_spectrum = new float[QSamples];
_fSample = AudioSettings.outputSampleRate;
_audioRange.fillAmount = 0;
if (Microphone.devices.Length > 0) {
_audioSource = GetComponent<AudioSource>();
_audioSource.outputAudioMixerGroup = _audioMixerMic;
_audioSource.clip = Microphone.Start(null, true, 10, 44100);
_audioSource.loop = true;
while (!(Microphone.GetPosition(null) > 0)) {
_audioSource.Play();
}
isReady = true;
}
}
void Update() {
if(isReady) {
AnalyzeSound();
}
}
void AnalyzeSound() {
_audioSource.GetOutputData(_samples, 0); // fill array with samples
int i;
float sum = 0;
for (i = 0; i < QSamples; i++) {
sum += _samples[i] * _samples[i]; // sum squared samples
}
rmsVal = Mathf.Sqrt(sum / QSamples); // rms = square root of average
dbVal = 20 * Mathf.Log10(rmsVal / RefValue); // calculate dB
if (dbVal < -160) dbVal = -160; // clamp it to -160dB min
// get sound spectrum
_audioSource.GetSpectrumData(_spectrum, 0, FFTWindow.BlackmanHarris);
float maxV = 0;
var maxN = 0;
for (i = 0; i < QSamples; i++) { // find max
if (!(_spectrum[i] > maxV) || !(_spectrum[i] > Threshold))
continue;
maxV = _spectrum[i];
maxN = i; // maxN is the index of max
}
float freqN = maxN; // pass the index to a float variable
if (maxN > 0 && maxN < QSamples - 1) { // interpolate index using neighbours
var dL = _spectrum[maxN - 1] / _spectrum[maxN];
var dR = _spectrum[maxN + 1] / _spectrum[maxN];
freqN += 0.5f * (dR * dR - dL * dL);
}
pitchVal = freqN * (_fSample / 2) / QSamples; // convert index to frequency
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment