⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 discretefouriertransform.cpp

📁 游戏音频程序设计-Beginning.Game.Audio.Programming
💻 CPP
字号:
// DiscreteFourierTransform.cpp: implementation of the 
// CDiscreteFourierTransform class.
//
//////////////////////////////////////////////////////////////////////

#include "DiscreteFourierTransform.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

namespace AudioEngine {

CDiscreteFourierTransform::CDiscreteFourierTransform(int bufsize, int samplerate, int bitspersample, int channels) : 
  m_BufSize(bufsize), m_SampleRate(samplerate), m_BitsPerSample(bitspersample), m_NumChannels(channels)
{
  // make space for buffers
  m_Input = new float[bufsize];
  m_FreqOutput = new float[(bufsize/2)+1];
  m_AmpOutput = new float[(bufsize/2)+1];

  // we know already what the frequencies of each bin will be
  for (int bin=0; bin < m_BufSize/2; bin++) {
    m_FreqOutput[bin] = (float)bin * m_SampleRate / m_BufSize;
  }
}

CDiscreteFourierTransform::~CDiscreteFourierTransform()
{
  delete[] m_Input;
  delete[] m_FreqOutput;
  delete[] m_AmpOutput;
}

void CDiscreteFourierTransform::LoadInputData(unsigned char *data)
{
  // convert each data point from 0-255 to floating point -1..1
  if (m_BitsPerSample == 8) {
    for (int q=0; q < m_BufSize; q++) {
      float d = data[q*m_NumChannels];
      m_Input[q] = (d-127.0f)/127.0f;
      if (m_Input[q] < -1.0f) m_Input[q] = -1.0f;
      if (m_Input[q] >  1.0f) m_Input[q] =  1.0f;
    }
  }
  else if (m_BitsPerSample == 16) {
    short int *sidata = reinterpret_cast<short int *>(data);
    for (int q=0; q < m_BufSize; q++) {
      float d = sidata[q*m_NumChannels];
      m_Input[q] = (d-32767.0f)/32767.0f;
      if (m_Input[q] < -1.0f) m_Input[q] = -1.0f;
      if (m_Input[q] >  1.0f) m_Input[q] =  1.0f;
    }
  }
  else {
    // not supported
    for (int q=0; q < m_BufSize; q++) { m_Input[q] = 0.0f; }
  }
    
}

void CDiscreteFourierTransform::PerformSlowFourierTransform()
{
  for (int bin = 0; bin <= m_BufSize/2; bin++) { 
    float cosAmp = 0.0f;
    float sinAmp = 0.0f;
    for (int k = 0; k < m_BufSize; k++) { 
      float x = 2.0f * M_PI * (float)bin * (float)k / (float)m_BufSize; 
      sinAmp += m_Input[k] * sin(x); 
      cosAmp += m_Input[k] * cos(x); 
    }
    m_AmpOutput[bin] = sqrt(sinAmp*sinAmp + cosAmp*cosAmp);
  }
}

} // namespace

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -