Berhoh

Audio Visualizer

Oct 11th, 2017
324
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void EffectWaveform::Update(double deltaTime)
  2. {
  3.     auto sound = Simulator::Instance->GetSound();
  4.     auto system = Simulator::Instance->GetSystem();
  5.     auto dsp = Simulator::Instance->GetDSP();
  6.     double timerMargin = 0.04;
  7.  
  8.     //WAVEFORM
  9.     m_WaveTimer += deltaTime;
  10.  
  11.     if (m_WaveTimer > timerMargin && sound != nullptr)
  12.     {
  13.         m_WaveTimer -= timerMargin;
  14.  
  15.         //Get format
  16.         FMOD_SOUND_TYPE type;
  17.         FMOD_SOUND_FORMAT format;
  18.         int channels, bits;
  19.         sound->getFormat(&type, &format, &channels, &bits);
  20.  
  21.         //Get software format
  22.         int sampleRate;
  23.         system->getSoftwareFormat(&sampleRate, nullptr, nullptr);
  24.  
  25.         //Get length
  26.         unsigned int length = 0;
  27.         sound->getLength(&length, FMOD_TIMEUNIT_MS);
  28.  
  29.         //Get dsp data
  30.         float frequency;
  31.         dsp->getParameterFloat(FMOD_DSP_FFT_DOMINANT_FREQ, &frequency, 0, 0);
  32.  
  33.         FMOD_DSP_PARAMETER_FFT *data;
  34.         char s[256];
  35.         unsigned int len;
  36.         dsp->getParameterData(FMOD_DSP_FFT_SPECTRUMDATA, (void**)(&data), &len, s, 256);
  37.  
  38.         //Get wave data
  39.         auto windowsize = 1024;
  40.  
  41.         auto ch = data->numchannels;
  42.         auto ln = data->length;
  43.  
  44.         m_WaveformLeft.clear();
  45.         m_WaveformRight.clear();
  46.  
  47.         if (ch > 0 && ln > 0)
  48.         {
  49.             auto largest = 0.0f;
  50.             auto resize = 1.0f;
  51.             auto localVol = Simulator::Instance->GetVolume();
  52.             if (localVol > 0.0f) resize = 1.0f / localVol;
  53.  
  54.             for (int channel = 0; channel < ch; ++channel)
  55.             {
  56.                 for (int bin = 0; bin < ln / 8; ++bin)
  57.                 {
  58.                     auto val = data->spectrum[channel][bin] * 10.0f;
  59.  
  60.                     if (val > largest) largest = val;
  61.  
  62.                     if (channel == 0)
  63.                         m_WaveformLeft.push_back(val*resize);
  64.                     else if (channel == 1)
  65.                         m_WaveformRight.push_back(val*resize);
  66.                 }
  67.             }
  68.  
  69.             Simulator::Instance->SetCurrentVolume(largest*resize);
  70.         }
  71.     }
  72. }
RAW Paste Data