fftsharp

How to calculate FFT in C# with FFTSharp

  • 3 min

FFTSharp is a .NET signal processing library that provides functions for performing Fast Fourier Transforms (FFT) and other signal processing algorithms.

The Fourier Transform is a mathematical tool that allows converting a signal from the time domain to its representation in the frequency domain. Even if the operation doesn’t sound familiar, you’ve probably used it, for example, when using an equalizer to adjust “the bass and treble” in an audio player.

In the case of sampled (discretized) signals, the equivalent is the DFT (Discrete Fourier Transform). On the other hand, the FFT (Fast Fourier Transform) is an algorithm for efficiently computing the DFT and its inverse, computationally.

FFT is a widely used technique in signal processing, with applications in a vast number of cases. It is used from processing audio, image, or video signals to analyzing seismic and astronomical data.

FFTSharp allows us to implement these functionalities easily in a .NET application, including.

  • Fast Fourier Transforms (FFT) with high precision and speed
  • Functions to calculate power spectra, phase spectra, and other related calculations
  • Functions to apply analysis windows and filtering to signals
  • Functions to perform convolution and correlation operations

It is designed to be easy to use and offer fast and precise performance. Therefore, it is an excellent option when we need to perform signal processing. Typically audio and images, although it is useful for any data series.

How to Use FFTSharp

We can add the library to a .NET project easily, through the corresponding Nuget package.

Install-Package FftSharp

Now we can use FFTSharp on a data series, as follows.

double[] data = { 1, 2, 3, 4, 5, 4, 3, 2, 1 };

var spectrum = FftSharp.FFO.Power(data);
for (int i = 0; i < spectrum.Length; i++)
{
    Console.WriteLine($"Frequency: {i}, Power: {spectrum[i]}");
}
Copied!

Here is an example of how to use it on a sampled audio wave, along with the ScottPlot library to graph the data.

// sample audio with tones at 2, 10, and 20 kHz plus white noise
double[] signal = FftSharp.SampleData.SampleAudio1();
int sampleRate = 48_000;

// plot the sample audio
var plt = new ScottPlot.Plot(400, 200);
plt.AddSignal(signal, sampleRate / 1000.0);
plt.YLabel("Amplitude");
plt.Margins(0);
plt.SaveFig("time-series.png");
Copied!

The project’s page explains the different options and more examples. They also provide a Demo application in the repository to test the functionality with simulated sound, and another using real audio obtained with a microphone.