synthberry
Software MIDI synthesizer for the Raspberry Pi.
 All Classes Functions
wave.cpp
1 #include <cstdlib>
2 #include <cmath>
3 #include "wave.h"
4 
5 template <class SampleType> Wave<SampleType>::Wave(uint16_t bitrate) :
6  buffer(nullptr),
7  bufferSize(0),
8  bitrate(bitrate),
9  changed(true),
10  lowestFreq(0)
11 {
12 }
13 
14 template <class SampleType> Wave<SampleType>::~Wave()
15 {
16  if(buffer)
17  free(buffer);
18 }
19 
28 template <class SampleType> void Wave<SampleType>::setNewFormula(FormulaFunction func)
29 {
30  formula.clear();
31  changed = true;
32  lowestFreq = 0;
33  addToFormula(func);
34 }
35 
43 template <class SampleType> void Wave<SampleType>::addToFormula(FormulaFunction func)
44 {
45  changed = true;
46  formula.push_back(func);
47 }
48 
61 template <class SampleType> void Wave<SampleType>::setLowestFrequency(float freq)
62 {
63  if((freq < lowestFreq) || (lowestFreq == 0)) {
64  changed = true;
65  lowestFreq = freq;
66  bufferSize = std::ceil(bitrate/freq) * sizeof(SampleType);
67  if(buffer)
68  free(buffer);
69  buffer = static_cast<SampleType *>(malloc(bufferSize));
70  if(buffer == nullptr)
71  throw std::bad_alloc();
72  }
73 }
74 
83 template <class SampleType> float Wave<SampleType>::getLowestFrequency()
84 {
85  return lowestFreq;
86 }
87 
98 template <class SampleType> void Wave<SampleType>::updateBuffer()
99 {
100  if(changed) {
101  changed = false;
102  for(auto func : formula)
103  func(buffer, bufferSize, bitrate);
104  }
105 }