-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
134 lines (107 loc) · 2.45 KB
/
lib.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
var midi = require('midi');
var input = new midi.input();
var output = new midi.output();
// receive MIDI Clock
input.ignoreTypes(true, false, true);
// set up receiving messages, transform and send
// remember last send value
(function () {
var previousSendValue;
input.on('message', function(deltaTime, message) {
// midi clock message
if (message[0] === 248) {
// var bpm = 60 / (24 * deltaTime)
var bpm = 2.5 / deltaTime;
if (bpm < 60) {
bpm = bpm * 2;
}
else if (bpm > 187) {
bpm = bpm / 2;
}
var value = Math.round(bpm - 60);
if (value != previousSendValue) {
output.sendMessage([config.message.status, config.message.control, value]);
previousSendValue = value;
}
}
});
}());
var isRunning = false;
var config = {
message: {
command: 176, // control change
control: 1,
status: calcStatus(0) // default channel: 0
},
ports: {
in: undefined,
out: undefined
}
};
module.exports = {
setChannel: setChannel,
setControl: setControl,
getInputPorts: getInputPorts,
getOutputPorts: getOutputPorts,
setInputPort: setInputPort,
setOutputPort: setOutputPort,
start: start,
stop: stop
};
function calcStatus(channel) {
return (176 & 0xF0) | (channel & 0x0F);
}
function setControl(control) {
config.message.control = control;
}
function setChannel(channel) {
config.message.status = calcStatus(channel);
}
function getInputPorts() {
return getPorts(input);
}
function getOutputPorts() {
return getPorts(output);
}
function getPorts(inOrOut) {
var inputPortCount = inOrOut.getPortCount();
var ports = [];
for (var i = 0; i < inputPortCount; i++) {
ports.push({ id: i, name: inOrOut.getPortName(i)});
}
return ports;
}
function setInputPort(port) {
var portId = port.id || port;
if (config.ports.in !== portId) {
config.ports.in = portId;
}
if (isRunning) {
stop();
start();
}
}
function setOutputPort(port) {
var portId = port.id || port;
if (config.ports.out !== portId) {
config.ports.out = portId;
}
if (isRunning) {
stop();
start();
}
}
function start() {
if (isRunning === false && config.ports.in !== undefined && config.ports.out !== undefined) {
input.openPort(config.ports.in);
output.openPort(config.ports.out);
isRunning = true;
}
}
function stop() {
if (isRunning) {
input.closePort();
output.closePort();
isRunning = false;
}
}