如何处理 FFT 的 NaN 结果?

问题描述 投票:0回答:1

我正在尝试实现一个函数,它接受一个 wav 文件,通过 AForge 的 FFT 运行 100 秒的音频。当我更改偏移量以改变我通过 FFT 计算的音频位置时,有时我会得到可以在图表中显示的结果,但大多数时候我会得到一个复杂的 NaN 数组。为什么会这样?

这是我的代码。

    public double[] test()
    {

        OpenFileDialog file = new OpenFileDialog();
        file.ShowDialog();
        WaveFileReader reader = new WaveFileReader(file.FileName);

        byte[] data = new byte[reader.Length];
        reader.Read(data, 0, data.Length);

        samepleRate = reader.WaveFormat.SampleRate;
        bitDepth = reader.WaveFormat.BitsPerSample;
        channels = reader.WaveFormat.Channels;

        Console.WriteLine("audio has " + channels + " channels, a sample rate of " + samepleRate + " and bitdepth of " + bitDepth + ".");


        float[] floats = new float[data.Length / sizeof(float)];
        Buffer.BlockCopy(data, 0, floats, 0, data.Length);

        size = 2048;

        int inputSamples = samepleRate / 100;
        int offset = samepleRate * 15 * channels;
        int y = 0;
        Complex[] complexData = new Complex[size];


        float[] window = CalcWindowFunction(inputSamples);
        for (int i = 0; i < inputSamples; i++)
        {

            complexData[y] = new Complex(floats[i * channels + offset] * window[i], 0);
            y++;
        }

        while (y < size)
        {
            complexData[y] = new Complex(0, 0);
            y++;
        }


        FourierTransform.FFT(complexData, FourierTransform.Direction.Forward);


        double[] arr = new double[complexData.Length];

        for (int i = 0; i < complexData.Length; i++)
        {
            arr[i] = complexData[i].Magnitude;
        }

        Console.Write("complete, ");

        return arr;

    }

    private float[] CalcWindowFunction(int inputSamples)
    {
        float[] arr = new float[size];
        for(int i =0; i<size;i++){

         arr[i] = 1;   

        }
        return arr;
    }
c# signal-processing fft
1个回答
3
投票

NaN 的复数数组通常是 FFT 的一个(或多个)输入为 NaN 的结果。要进行调试,您可以在 FFT 之前检查输入数组中的所有值,以确保它们在给定音频输入缩放比例的某个有效范围内。

© www.soinside.com 2019 - 2024. All rights reserved.