-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOscillator.cpp
More file actions
96 lines (89 loc) · 2.3 KB
/
Oscillator.cpp
File metadata and controls
96 lines (89 loc) · 2.3 KB
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
#include "Oscillator.h"
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::updateIncrement() {
mPhaseIncrement = mFrequency * 2 * mPI / mSampleRate;
}
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;
if(isMuted) return value;
switch (mOscillatorMode) {
case OSCILLATOR_MODE_SINE:
value = cos(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;
}