c# - 带有 NAudio 和 WPFSoundVisualizationLib 的频谱分析仪

标签 c# audio fft naudio

我正在研究 C#4.0/WPF 实时频谱分析仪(作为另一个项目的基础)。我使用 NAudio 最新版本在声卡上获得实时音频输出,并使用 WPFSoundVisualizationLib (http://wpfsvl.codeplex.com/) 用于频谱分析器 WPF 控件。有了这个神奇的工具,工作就快完成了,但它不能正常工作:-(

我有一个功能正常的 Spectrum,但信息不是权利,我不明白问题出在哪里...(我将我的 Spectrum 与 Equalify 进行了比较,Equalify 是 Spotify 的 Spectrum/均衡器,但我不知 Prop 有相同的行为)

这是我的主课:

using System;
using System.Windows;
using WPFSoundVisualizationLib;

namespace MySpectrumAnalyser
{
    public partial class MainWindow : Window
    {
        private RealTimePlayback _playback;
        private bool _record;

        public MainWindow()
        {
            InitializeComponent();
            this.Topmost = true;
            this.Closing += MainWindow_Closing;
            this.spectrum.FFTComplexity = FFTDataSize.FFT2048;
            this.spectrum.RefreshInterval = 60;
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this._record)
            {
                this._playback.Stop();
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (this._playback == null)
            {
                this._playback = new RealTimePlayback();
                this.spectrum.RegisterSoundPlayer(this._playback);
            }

            if (!this._record)
            {
                this._playback.Start();
                this.Dispatcher.Invoke(new Action(delegate
                {
                    this.btnRecord.Content = "Stop";
                }));
            }
            else
            {
                this._playback.Stop();
                this.Dispatcher.Invoke(new Action(delegate
                {
                    this.btnRecord.Content = "Start";
                }));
            }

            this._record = !this._record;
        }
    }
}

还有我的环回分析器(它实现了 ISpectrumPlayer 以与 WPFSoundVisualizationLib Spectrum 控件一起使用)。

LoopbackCapture继承NAudio.CoreAudioApi.WasapiCapture。

从 Wasapi 接收到的数据是一个字节数组(32 位 PCM,44.1kHz,2 channel ,每个样本 32 位)

using NAudio.Dsp;
using NAudio.Wave;
using System;
using WPFSoundVisualizationLib;

namespace MySpectrumAnalyser
{
    public class RealTimePlayback : ISpectrumPlayer
    {
        private LoopbackCapture _capture;
        private object _lock;
        private int _fftPos;
        private int _fftLength;
        private Complex[] _fftBuffer;
        private float[] _lastFftBuffer;
        private bool _fftBufferAvailable;
        private int _m;

        public RealTimePlayback()
        {
            this._lock = new object();

            this._capture = new LoopbackCapture();
            this._capture.DataAvailable += this.DataAvailable;

            this._m = (int)Math.Log(this._fftLength, 2.0);
            this._fftLength = 2048; // 44.1kHz.
            this._fftBuffer = new Complex[this._fftLength];
            this._lastFftBuffer = new float[this._fftLength];
        }

        public WaveFormat Format
        {
            get
            {
                return this._capture.WaveFormat;
            }
        }

        private float[] ConvertByteToFloat(byte[] array, int length)
        {
            int samplesNeeded = length / 4;
            float[] floatArr = new float[samplesNeeded];

            for (int i = 0; i < samplesNeeded; i++)
            {
                floatArr[i] = BitConverter.ToSingle(array, i * 4);
            }

            return floatArr;
        }

        private void DataAvailable(object sender, WaveInEventArgs e)
        {
            // Convert byte[] to float[].
            float[] data = ConvertByteToFloat(e.Buffer, e.BytesRecorded);

            // For all data. Skip right channel on stereo (i += this.Format.Channels).
            for (int i = 0; i < data.Length; i += this.Format.Channels)
            {
                this._fftBuffer[_fftPos].X = (float)(data[i] * FastFourierTransform.HannWindow(_fftPos, _fftLength));
                this._fftBuffer[_fftPos].Y = 0;
                this._fftPos++;

                if (this._fftPos >= this._fftLength)
                {
                    this._fftPos = 0;

                    // NAudio FFT implementation.
                    FastFourierTransform.FFT(true, this._m, this._fftBuffer);

                    // Copy to buffer.
                    lock (this._lock)
                    {
                        for (int c = 0; c < this._fftLength; c++)
                        {
                            this._lastFftBuffer[c] = this._fftBuffer[c].X;
                        }

                        this._fftBufferAvailable = true;
                    }
                }
            }
        }

        public void Start()
        {
            this._capture.StartRecording();
        }

        public void Stop()
        {
            this._capture.StopRecording();
        }

        public bool GetFFTData(float[] fftDataBuffer)
        {
            lock (this._lock)
            {
                // Use last available buffer.
                if (this._fftBufferAvailable)
                {
                    this._lastFftBuffer.CopyTo(fftDataBuffer, 0);
                    this._fftBufferAvailable = false;
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public int GetFFTFrequencyIndex(int frequency)
        {
            int index = (int)(frequency / (this.Format.SampleRate / this._fftLength / this.Format.Channels));
            return index;
        }

        public bool IsPlaying
        {
            get { return true; }
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
    }
}

WPF 控件每 60 毫秒调用一次 GetFFTData 以更新 Spectrum。

最佳答案

我回答这个问题可能有点晚了,但我们到了。

你快到了。您只需提供 FFT 返回的复数的幅度而不是 X 值。

所以在 for 循环中,而不是这样:

this._lastFftBuffer[c] = this._fftBuffer[c].X;

这样做:

float amplitude = (float)Math.Sqrt(this._fftBuffer[c].X * this._fftBuffer[c].X + this._fftBuffer[c].Y * this._fftBuffer[c].Y);
this._lastFftBuffer[c] = amplitude;

干杯!

关于c# - 带有 NAudio 和 WPFSoundVisualizationLib 的频谱分析仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398802/

相关文章:

c# - 'volatile' 关键字在 C# 中是否仍然损坏?

iphone - 如何将AudioQueuePause与AudioQueueGetCurrentTime结合使用以在iPhone SDK中恢复音频播放?

Python scipy.fftpack.rfft 频点映射

image-processing - opencv dft仅适用于2的幂的图像尺寸

signal-processing - 快速傅里叶变换应用窗口和重叠

c# - 将 eval 传递给 javascript

c# - 我可以对同一个端点使用普通的 http 和 https 吗

c# - 如何在 Xamarin.Forms ListView 下添加按钮

macos - 核心音频和 Phantom 设备 ID

macos - 如何以编程方式列出当前在 Mac OS 10.6 上使用默认声音输出的进程