-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
69 lines (60 loc) · 1.3 KB
/
sketch.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
// Author: Johnny Dinh
const model_url =
'https://cdn.jsdelivr.net/gh/ml5js/ml5-data-and-models/models/pitch-detection/crepe/';
let pitch;
let mic;
let frequency = 0;
let threshold = 1;
let notes =
{'low_e' : 82.41,
'a' : 110.00,
'd' : 146.83,
'g' : 196.00,
'b' : 246.94,
'high_e' : 329.63
}
function setup() {
createCanvas(400, 400);
audioContext = getAudioContext();
mic = new p5.AudioIn();
mic.start(listening);
}
function listening() {
console.log('Starting to listen...');
pitch = ml5.pitchDetection(model_url, audioContext, mic.stream, modelLoaded);
}
function myGetPitch(error, freq) {
console.log('Retrieving pitch...');
if (error) {
console.error(error);
}
else {
if (freq) {
console.log(freq);
frequency = freq;
}
pitch.getPitch(myGetPitch);
}
}
function modelLoaded() {
console.log('Loading model...');
pitch.getPitch(myGetPitch);
}
function draw() {
background(220);
let note = 1;
let smallest_diff = Infinity;
for (var n in notes) {
if (Math.abs(frequency - notes[n]) < smallest_diff)
{
note = n;
smallest_diff = Math.abs(frequency - notes[n])
}
}
if (smallest_diff < 30) {
textAlign(CENTER, CENTER);
fill(255);
textSize(64);
text(note, width / 2, height - 50);
}
}