拙网论坛

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 205|回复: 0

Calculating the FFT in C#

[复制链接]

949

主题

1001

帖子

3736

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
3736
发表于 2018-7-24 10:39:35 | 显示全部楼层 |阅读模式

With NAudio (light)

using NAudio.Wave; // for sound card access
using NAudio.Dsp; // for FastFourierTransform
// prepare the complex data which will be FFT'd
Complex[] fft_buffer = new Complex[fft_size];
for (int i=0; i < fft_size; i++)
{
    fft_buffer.X = (float)(unanalyzed_values* FastFourierTransform.HammingWindow(i, fft_size));
    fft_buffer.Y = 0;
}
// perform the FFT
FastFourierTransform.FFT(true, (int)Math.Log(fft_size, 2.0), fft_buffer);
// a list with FFT values
List<double> new_data = new List<double>();
for (int i = 0; i < spec_data[spec_data.Count - 1].Count; i++)
{
    // should this besqrt(X^2+Y^2)?
    double val;
    val = (double)fft_buffer.X+ (double)fft_buffer.Y;
    val = Math.Abs(val);
    if (checkBox1.Checked)val = Math.Log(val);
    new_data.Add(val);
}
With Accord (heavy)

Here is aminimal-case example how to convert an array of doubles into the frequencydomain using a Fast Fouriertransformation in C# (Visual Studio Community 2017). It usesthe Accord .NET library. Add areference to the Assembly Framework System.Numerics. Use NuGet toinstall Accord.Audio. example project:microphone FFT
using System.Numerics;
public double[] FFT(double[] data)
{
    int nPoints = data.Length; // whatever wemeasure must be a power of 2
    for (int i = 0; i < data.Length; i++) data = Math.Sin(i); // fill it withsome data
    double[] fft = new double[nPoints]; // this is wherewe will store the output (fft)
    Complex[] fftComplex = new Complex[nPoints]; // the FFTfunction requires complex format
    for (int i = 0; i < data.Length; i++)
        fftComplex = new Complex(data, 0.0); // make itcomplex format
    Accord.Math.FourierTransform.FFT(fftComplex, Accord.Math.FourierTransform.Direction.Forward);
    for (int i = 0; i < data.Length; i++)
        fft = fftComplex.Magnitude;// back to double
    return fft;
    //todo: this couldbe much faster by reusing variables
}

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|抱朴守拙BBS

GMT+8, 2025-5-26 07:35 , Processed in 0.190428 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表