Hi guys, I am trying to achieve frequency detection of 15k, 17k and19k but there will always be noise and distance problem which distort the frequency received how can i improve it. The scripts actually works but i want to further improve the detection.
Really need help on this… Thanks guys!
using UnityEngine;
using System.Collections;
public class FrequencyDetector : MonoBehaviour
{
private GameObject _gameObject;
public FrequencyMenu frequencyMenu;
private int _samplingCount = 2048;
private float _frequency;
private int _samplerate;
private float[] _data;
public tk2dTextMesh freqText;
void Awake ()
{
_gameObject = gameObject;
Application.targetFrameRate = 60;
AudioSettings.outputSampleRate = 44100;
_data = new float[_samplingCount];
_samplerate = AudioSettings.outputSampleRate;
}
void Start ()
{
initMic();
}
void Update ()
{
analyzeSound();
findRange();
setFreqText();
}
private void setFreqText()
{
freqText.text = _frequency.ToString();
freqText.Commit();
}
public void initMic()
{
Application.RequestUserAuthorization (UserAuthorization.Microphone);
if (Application.HasUserAuthorization (UserAuthorization.Microphone))
{
audio.loop = true;
audio.mute = true;
audio.clip = Microphone.Start(null, true, 1, _samplerate);
while (!(Microphone.GetPosition(null) > 0))
audio.Play();
}
}
public void StartMic()
{
_gameObject.SetActive(true);
audio.clip = Microphone.Start(null, true, 1, _samplerate);
while (!(Microphone.GetPosition(null) > 0))
audio.Play();
}
public void StopMic()
{
Microphone.End(null);
_gameObject.SetActive(false);
}
private void analyzeSound()
{
audio.GetSpectrumData(_data, 0, FFTWindow.BlackmanHarris);
float max = 0f;
int maxN = 0;
for (int i = 0; i < _samplingCount; ++i)
{
if (_data[i] > max)
{
max = _data[i];
maxN = i;
}
}
_frequency = maxN * (_samplerate / 2) / _samplingCount;
}
private void findRange()
{
if ((_frequency > 18970 && _frequency < 19030) ||
(_frequency > 16970 && _frequency < 17030) ||
(_frequency > 14970 && _frequency < 15030))
{
// Do something
}
else if ((_frequency > 19070 && _frequency < 19130) ||
(_frequency > 17070 && _frequency < 17130) ||
(_frequency > 15070 && _frequency < 15130))
{
// Do something
}
else if ((_frequency > 19170 && _frequency < 19230) ||
(_frequency > 17170 && _frequency < 17230) ||
(_frequency > 15170 && _frequency < 15230))
{
// Do something
}
else if ((_frequency > 19570 && _frequency < 19630) ||
(_frequency > 17570 && _frequency < 17630) ||
(_frequency > 15570 && _frequency < 15630))
{
// Do something
}
else if ((_frequency > 19670 && _frequency < 19730) ||
(_frequency > 17670 && _frequency < 17730) ||
(_frequency > 15370 && _frequency < 15430))
{
// Do something
}
else if ((_frequency > 19770 && _frequency < 19830) ||
(_frequency > 17770 && _frequency < 17830) ||
(_frequency > 15270 && _frequency < 15330))
{
// Do something
}
}
}