-
Notifications
You must be signed in to change notification settings - Fork 1
/
NoteState.js
106 lines (78 loc) · 2.56 KB
/
NoteState.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
/* eslint-disable no-console */
const note = require ('tonal-freq').note
// Holds single pitch data to be averaged
let rawPitchArray = []
// initialize our boolean
let inNote = false
function debounce(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow){
return func.apply(context, args);
}
};
}
/*
nullsSinceLastPitch is an attempt to facilitate junk pitch dumping when the
pitches detected aren't actually long enough to have been a valid note and
shouldn't be taken into account when the next note actually does arrive
*/
// Should be set to zero when a pitch is hit and otherwise tracks nulls since last pitch
let nullsSinceLastPitch = 0
function noteReturn () {
// Sum the pitches and pop them, return a pitch
var runningSum = 0
var arrayLength = rawPitchArray.length
if (arrayLength<=4){
// dumps too short sections of pitch data
rawPitchArray = []
// console.log("array length too short")
return null
}
while (rawPitchArray.length) {
var setOfPitches = rawPitchArray.pop()
runningSum += setOfPitches
}
// Then process the averaged pitch and find its note value
var averagePitch = runningSum / arrayLength
// console.log(note(averagePitch))
// TODO: insert a callback here
return note(averagePitch)
}
let debouncedNoteReturn = debounce(noteReturn,500, true)
function pitchStateManagement(pitch){
if (pitch == null) {
nullsSinceLastPitch += 1
}
if (nullsSinceLastPitch === 5) {
rawPitchArray = []
}
if ((pitch == null) && inNote) {
inNote = false
// Debounced return function
let returnedNote = debouncedNoteReturn()
// console.log(returnedNote)
return returnedNote
} else if (!(pitch == null) && !inNote) {
// We're starting a new note
rawPitchArray.push(pitch)
inNote = true
nullsSinceLastPitch = 0
return null
} else if (!(pitch == null) && inNote) {
rawPitchArray.push(pitch)
return null
}
}
module.exports = {
getNote: pitchStateManagement
}