69 lines
1.5 KiB
C#
69 lines
1.5 KiB
C#
using System;
|
|
using SoundAnalysis;
|
|
using SoundCapture;
|
|
|
|
namespace FrequencyDetection
|
|
{
|
|
public class SoundFrequencyInfoSource : FrequencyInfoSource
|
|
{
|
|
readonly SoundCaptureDevice _device;
|
|
Adapter _adapter;
|
|
|
|
public SoundFrequencyInfoSource(SoundCaptureDevice device)
|
|
{
|
|
_device = device;
|
|
}
|
|
|
|
public override void Listen()
|
|
{
|
|
_adapter = new Adapter(this, _device);
|
|
_adapter.Start();
|
|
}
|
|
|
|
public override void Stop()
|
|
{
|
|
_adapter.Stop();
|
|
}
|
|
|
|
class Adapter : SoundCaptureBase
|
|
{
|
|
readonly SoundFrequencyInfoSource _owner;
|
|
|
|
const double MinFreq = 60;
|
|
const double MaxFreq = 1300;
|
|
|
|
internal Adapter(SoundFrequencyInfoSource owner, SoundCaptureDevice device)
|
|
: base(device)
|
|
{
|
|
_owner = owner;
|
|
}
|
|
|
|
protected override void ProcessData(short[] data)
|
|
{
|
|
double[] x = new double[data.Length];
|
|
for (int i = 0; i < x.Length; i++)
|
|
{
|
|
x[i] = data[i];
|
|
}
|
|
|
|
double[] spectr = FftAlgorithm.Calculate(x);
|
|
int index = 0;
|
|
double max = spectr[0];
|
|
int usefullMaxSpectr = Math.Min(spectr.Length,
|
|
(int)(MaxFreq * spectr.Length / SampleRate) + 1);
|
|
for (int i = 1; i < usefullMaxSpectr; i++)
|
|
{
|
|
if (max < spectr[i])
|
|
{
|
|
max = spectr[i]; index = i;
|
|
}
|
|
}
|
|
|
|
double freq = (double)SampleRate * index / spectr.Length;
|
|
if (freq < MinFreq) freq = 0;
|
|
|
|
_owner.OnFrequencyDetected(new FrequencyDetectedEventArgs(freq));
|
|
}
|
|
}
|
|
}
|
|
} |