-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetronome.js
81 lines (67 loc) · 2.34 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
async function load_time_signatures(time_signature) {
const response = await fetch ('time_signatures.json');
const data = await response.json();
return data.time_signatures;
}
async function get_time_signatures() {
let time_signatures = await load_time_signatures();
return time_signatures;
}
//function generate_pattern(time_signature) {
// return [1, 1, 1, 1]
//}
//
//function generate_pattern_subdivided(time_signature) {
// return [1, 2, 2, 1, 2, 2, 1, 2, 2]
//}
export function Metronome(time_signature, beats_per_minute, subdivided) {
this.is_running = false;
this.subdivided = subdivided;
this.click_strong = new Audio('audio_files/click_strong.wav');
this.click_weak = new Audio('audio_files/click_weak.wav');
this.beats_per_minute = beats_per_minute;
this.init = async () => {
this.time_signatures = await get_time_signatures();
this.time_signature = this.time_signatures[time_signature];
};
// Call the init method to asynchronously initialize the object
this.init();
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export async function metronome_start(metronome) {
let STRONG_BEAT = 1;
let WEAK_BEAT = 2;
let pattern = []
let position = 0;
let delay_ms = 0;
let beats_per_minute = metronome.beats_per_minute;
if (metronome.subdivided) {
let subdivisions_per_beat = metronome.time_signature['subdivisions_per_beat'];
delay_ms = 1000 * 60 / beats_per_minute / subdivisions_per_beat;
pattern = metronome.time_signature['subdivision_pattern'];
} else {
delay_ms = 1000 * 60 / beats_per_minute;
console.log(metronome.time_signature['num_beats']);
for (let i = 0; i < metronome.time_signature['num_beats']; i++) {
pattern.push(STRONG_BEAT);
}
}
console.log("Made it Here")
metronome.is_running = true
console.log(pattern);
while (metronome.is_running) {
position = (position + 1) % pattern.length;
if (pattern[position] == STRONG_BEAT) {
await metronome.click_strong.play()
}
if (pattern[position] == WEAK_BEAT) {
await metronome.click_weak.play()
}
await sleep(delay_ms);
}
}
export async function metronome_stop(metronome) {
metronome.is_running = false;
}