Hi,
Thanks for looking at this post! I’m a beginner looking for help in getting a Microphone / GetSpectrumData code working.
In 2017 I made a simple script to get microphone audio and use GetSpectrumData. The code worked fine at the time.
Come 2020, I’ve updated to the latest version of Unity but I can no longer get the code to run. After crawling through various official guides and forums it seems like my code should run ok, but it is not working.
Specifically, there are no run errors, but the output variable spectrum is not updating each update with dynamic values. Instead _spectrum returns with the same data roughly following a power-law (and not resembling the audio - see cyan line in image). This suggests to be the GetSpectrumData part of the code is working, but perhaps my Microphone is not working?
[157592-screenshot-2020-04-24-at-220453.png*_|157592]
Here’s the code. I’d appreciate any advice on how to fix it or how to debug it further.
Thanks in advance!! best, Rob
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(AudioSource))]
public class Notable : MonoBehaviour {
public AudioSource _audioSrc;
public float[] _spectrum = new float[512];
// Use this for initialization
void Start () {
foreach (string device in Microphone.devices) {
Debug.Log ("Name: " + device);
}
if (_audioSrc == null)
_audioSrc = GetComponent<AudioSource>();
if (_audioSrc == null)
_audioSrc = gameObject.AddComponent<AudioSource>();
_audioSrc.clip = Microphone.Start("Built-in Microphone", true, 1, 44100);
while (!(Microphone.GetPosition(null) > 0)) { } // this line removes lag.
_audioSrc.loop = true;
_audioSrc.Play();
}
// Update is called once per frame
void Update () {
Debug.Log ("Spec0 is "+ _spectrum[0]);
_audioSrc.GetSpectrumData(_spectrum,0,FFTWindow.Rectangular);
Debug.Log ("SpecUpdt is "+ _spectrum[0]);
int i = 1;
while ( i < _spectrum.Length-1) {
Debug.DrawLine( new Vector3(i-1,_spectrum*+10,0), new Vector3(i, _spectrum[i+1] + 10, 0),Color.red);*
Debug.DrawLine( new Vector3(i-1,Mathf.Log(spectrum[i-1])+10,2), new Vector3(i,Mathf.Log(spectrum*) + 10,2),Color.cyan);
Debug.DrawLine( new Vector3(Mathf.Log(i-1),_spectrum[i-1]-10,1), new Vector3(Mathf.Log(i),_spectrum-10,1),Color.green);
Debug.DrawLine( new Vector3(Mathf.Log(i-1),Mathf.Log (_spectrum[i-1]),3), new Vector3(Mathf.Log(i),Mathf.Log (_spectrum),3),Color.yellow);*
* i++;*
* }*
* }*
}
_*