Reputation: 430
i want to display the frequency spectrum of a .wav (or .mp3) file. I stuck a little bit now and cant find anything good. I use C# with naudio nuget to handle the audio data and oxyplot to display the points (and the graph).
Initialisation:
AudioFileReader fileStream;
fileStream = new AudioFileReader(fileName);
private static List<List<double>> spec_data;
spec_data = new List<List<double>>();
private static List<short> unanalyzed_values = new List<short>();
audio read:
//8192, 4096, 2048, 1024
BUFFERSIZE = 4096;
var buffer = new byte[BUFFERSIZE];
int bytes_read = fileStream.Read(buffer, 0, buffer.Length);
int BYTES_PER_POINT = fileStream.WaveFormat.BitsPerSample / 8; //8Bit = 1Byte
for (int n = 0; n < BYTES_PER_POINT; n ++)
{
short[] values = new short[buffer.Length / BYTES_PER_POINT];
for (int i = 0; i < bytes_read; i += BYTES_PER_POINT)
{
//each byte become one value
values[i / BYTES_PER_POINT] = (short)((buffer[i + 1] << 8) | buffer[i + 0]);
}
unanalyzed_values.AddRange(values);
}
the chunk analysis:
// insert new data to the right-most (newest) position
List<double> new_data = new List<double>();
Complex[] fft_buffer = new Complex[BUFFERSIZE];
for (int i = 0; i < BUFFERSIZE; i++)
{
fft_buffer[i].X = (float)(unanalyzed_values[i] * FastFourierTransform.HammingWindow(i, BUFFERSIZE));
fft_buffer[i].Y = 0;
}
FastFourierTransform.FFT(true, (int)Math.Log(BUFFERSIZE, 2.0), fft_buffer);
for (int i = 0; i < fft_buffer.Length -1; i++)
{
double val;
val = (double)fft_buffer[i].X + (double)fft_buffer[i].Y;
val = Math.Abs(val);
new_data.Add(val);
}
new_data.Reverse();
spec_data.Insert(spec_data.Count, new_data);
Upvotes: 4
Views: 3779
Reputation: 430
Ok at the end i found a good nuget to realize that:
https://github.com/swharden/Spectrogram
https://www.nuget.org/packages/Spectrogram/
var spec = new Spectrogram.Spectrogram(
sampleRate: 44100,
fftSize: 4096, //resolution size for the values
step: 200);
float[] values = Spectrogram.Tools.ReadWav(fileName);
spec.AddExtend(values);
// convert FFT to an image
bmp = spec.GetBitmap(
intensity: 0.5, //loudness filter
freqHigh: 200,
freqLow: 50,
showTicks: true,
colormap: Spectrogram.Colormap.grayscale);
the clue is to set the right intensity. That filter the loud voice-lines out of the noisy spectrogram.
Upvotes: 2