-
Notifications
You must be signed in to change notification settings - Fork 1
/
Oscillator.cpp
111 lines (100 loc) · 2.3 KB
/
Oscillator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#include "Oscillator.h"
double Oscillator::mSampleRate = 44100.0;
void Oscillator::setMode(OscillatorMode mode) {
mOscillatorMode = mode;
}
void Oscillator::setFrequency(double frequency) {
mFrequency = frequency;
updateIncrement();
}
void Oscillator::setSampleRate(double sampleRate) {
mSampleRate = sampleRate;
updateIncrement();
}
void Oscillator::generate(double* buffer, int nFrames) {
const double twoPI = 2 * mPI;
switch (mOscillatorMode) {
case OSCILLATOR_MODE_SINE:
for (int i = 0; i < nFrames; i++) {
buffer[i] = sin(mPhase);
mPhase += mPhaseIncrement;
while (mPhase >= twoPI) {
mPhase -= twoPI;
}
}
break;
case OSCILLATOR_MODE_SAW:
for (int i = 0; i < nFrames; i++) {
buffer[i] = 1.0 - (2.0 * mPhase / twoPI);
mPhase += mPhaseIncrement;
while (mPhase >= twoPI) {
mPhase -= twoPI;
}
}
break;
case OSCILLATOR_MODE_SQUARE:
for (int i = 0; i < nFrames; i++) {
if (mPhase <= mPI) {
buffer[i] = 1.0;
}
else {
buffer[i] = -1.0;
}
mPhase += mPhaseIncrement;
while (mPhase >= twoPI) {
mPhase -= twoPI;
}
}
break;
case OSCILLATOR_MODE_TRIANGLE:
for (int i = 0; i < nFrames; i++) {
double value = -1.0 + (2.0 * mPhase / twoPI);
buffer[i] = 2.0 * (fabs(value) - 0.5);
mPhase += mPhaseIncrement;
while (mPhase >= twoPI) {
mPhase -= twoPI;
}
}
break;
}
}
double Oscillator::nextSample() {
double value = 0.0;
switch (mOscillatorMode) {
case OSCILLATOR_MODE_SINE:
value = sin(mPhase);
break;
case OSCILLATOR_MODE_SAW:
value = 1.0 - (2.0 * mPhase / twoPI);
break;
case OSCILLATOR_MODE_SQUARE:
if (mPhase <= mPI) {
value = 1.0;
}
else {
value = -1.0;
}
break;
case OSCILLATOR_MODE_TRIANGLE:
value = -1.0 + (2.0 * mPhase / twoPI);
value = 2.0 * (fabs(value) - 0.5);
break;
}
mPhase += mPhaseIncrement;
while (mPhase >= twoPI) {
mPhase -= twoPI;
}
return value;
}
void Oscillator::setPitchMod(double amount) {
mPitchMod = amount;
updateIncrement();
}
void Oscillator::updateIncrement() {
double pitchModAsFrequency = pow(2.0, fabs(mPitchMod) * 14.0) - 1;
if (mPitchMod < 0) {
pitchModAsFrequency = -pitchModAsFrequency;
}
double calculatedFrequency = fmin(fmax(mFrequency + pitchModAsFrequency, 0), mSampleRate / 2.0);
mPhaseIncrement = calculatedFrequency * 2 * mPI / mSampleRate;
}