-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmetronome.js
235 lines (194 loc) · 6.33 KB
/
metronome.js
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
const DEFAULT_LOOKAHEAD_MS = 25;
const DEFAULT_SCHEDULE_S = 0.1;
const DEFAULT_BPM = 90;
const DEFAULT_TIME_SIGNITURE = 16;
const DEFAULT_NOTE_LENGTH = 0.05;
const DEFAULT_OSCILLATOR_TYPE = 'sine';
const DEFAULT_FREQUENCY = 220;
const MIN_FREQUENCY = 40;
const MINUTE = 15;
const DEFAULT_GAIN = 0;
const AudioContext = window.AudioContext || window.webkitAudioContext; //maybe change
const audioCtx = new AudioContext();
class Metronome {
constructor(
BPM = DEFAULT_BPM,
timeSigniture = DEFAULT_TIME_SIGNITURE,
gain = DEFAULT_GAIN) {
//User mutable
this._BPM = BPM;
this._timeSigniture = timeSigniture;
this._gain = gain;
this._pushNote = 0;
this._noteVolumes = [1, 1, 1, 1];
this._noteLength = DEFAULT_NOTE_LENGTH;
this._oscillatorType = DEFAULT_OSCILLATOR_TYPE;
this._frequency = DEFAULT_FREQUENCY;
//Functionally assigned
this._samplesArray = [];
this._samplesLoaded = false;
this._accentChecked = false;
//Internal values
this._notesInQueue = [];
this._playing = false;
this._timerID;
this._nextNoteTime = 0.0;
this._currentNote = 0;
this._lookahead = DEFAULT_LOOKAHEAD_MS;
this._scheduleAheadTime = DEFAULT_SCHEDULE_S;
};
//Client settings ----------------------------------------
set BPM(newBPM) {
this._BPM = Number(newBPM);
}
set timeSigniture(newTimeSigniture) {
this._timeSigniture = Number(newTimeSigniture);
}
updateAccentChecked() {
this._accentChecked ^= true;
}
set noteVolumes(volumesArray) {
this._noteVolumes = volumesArray;
}
set budge(time) {
this._pushNote = time;
}
set noteLength(time) {
this._noteLength = Number(time);
}
set oscillatorType(wave) {
let newWaveType;
switch (wave) {
case 'sine':
case 'square':
case 'sawtooth':
case 'triangle':
newWaveType = wave;
break;
default:
newWaveType = DEFAULT_OSCILLATOR_TYPE;
}
this._oscillatorType = newWaveType;
}
set frequency(freq) {
if (freq <= MIN_FREQUENCY) freq = MIN_FREQUENCY;
this._frequency = freq;
}
set gain(gain) {
this._noteVolumes = new Array(this._timeSigniture).fill(gain);
}
_valueChecks() {
while (this._noteVolumes.length < this._timeSigniture) {
this._noteVolumes = [...this._noteVolumes, ...this._noteVolumes]
}
}
start() {
if (!this._playing) {
this._currentNote = 0;
this._nextNoteTime = audioCtx.currentTime;
this._valueChecks();
this._scheduler();
this._playing = true;
}
}
stop() {
window.clearTimeout(this._timerID);
this._playing = false;
}
_nextNote() {
const secondsPerBeat = MINUTE / this._BPM;
this._nextNoteTime += secondsPerBeat;
this._currentNote++;
if (this._currentNote >= this._timeSigniture) {
this._currentNote = 0;
}
}
// This allows output of the notesInQueue array to sync with graphics
aListener(val) {};
registerListener(listener) {
this.aListener = listener;
}
_scheduleSamples(beatNumber, time) {
this._notesInQueue.push({ note: beatNumber, time: time });
this.aListener(this._notesInQueue, audioCtx.currentTime, this._samplesArray[0].name)
if (this._notesInQueue.length >= this._timeSigniture) this._notesInQueue.splice(0,1);
if (this._accentChecked && this._samplesArray.length >= 2) {
if (beatNumber === this._timeSigniture - 1) this._playSample(audioCtx, this._samplesArray[1].audioBuffer, this._noteVolumes[beatNumber]);
else this._playSample(audioCtx, this._samplesArray[0].audioBuffer, this._noteVolumes[beatNumber]);
} else {
this._playSample(audioCtx, this._samplesArray[0].audioBuffer, this._noteVolumes[beatNumber]);
}
}
_scheduleOscillator(beatNumber, time) {
this._notesInQueue.push({ note: beatNumber, time: time });
const oscillator = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);
oscillator.type = this._oscillatorType;
if (this._noteVolumes[beatNumber] === 0) {
gainNode.gain.setValueAtTime(0, audioCtx.currentTime)
}
if (this._accentChecked) {
if (beatNumber === this._timeSigniture - 1) oscillator.frequency.value = this._frequency * 2;
else oscillator.frequency.value = this._frequency;
} else if (!this._accentChecked) {
oscillator.frequency.value = this._frequency;
}
// if (this._noteVolumes[beatNumber] != 0) {
oscillator.start(time + this._pushNote);
oscillator.stop(time + this._noteLength + this._pushNote);
// }
}
_scheduler() {
let context;
if (!context) context = this;
function contextScheduler() {
while (context._nextNoteTime < audioCtx.currentTime + context._scheduleAheadTime) {
if (context._samplesLoaded) context._scheduleSamples(context._currentNote, context._nextNoteTime);
else context._scheduleOscillator(context._currentNote, context._nextNoteTime);
context._nextNote();
}
context._timerID = window.setTimeout(contextScheduler, context._lookahead);
}
contextScheduler()
}
//Deal with custom samples
loadSamples(urlArray) {
this._setUpSample(urlArray)
.then(samples => {
this._samplesArray = [...samples];
this._samplesLoaded = true;
})
}
async _loadSound(audioCtxParam, filePath) {
try {
const response = await fetch(filePath);
const arrayBuffer = await response.arrayBuffer()
const audioBuffer = await audioCtxParam.decodeAudioData(arrayBuffer);
return audioBuffer;
} catch (e) {
console.log(e);
}
};
async _setUpSample(urlArray) {
return Promise.all(urlArray.map(async path => {
let sampleHolder = {};
sampleHolder.audioBuffer = await this._loadSound(audioCtx, path);
sampleHolder.name = path.match(/([^\/]+)(?=\.\w+$)/)[0].replace(/-/, '_');
return sampleHolder;
}))
.then(data => data);
};
_playSample(audioCtxParam, audioBuffer, noteVolume = 1) {
const sampleSource = audioCtxParam.createBufferSource();
const gainNode = audioCtx.createGain();
sampleSource.buffer = audioBuffer;
sampleSource.connect(gainNode);
gainNode.connect(audioCtxParam.destination);
gainNode.gain.value = noteVolume;
sampleSource.start();
return sampleSource;
}
}
export default Metronome;