-
Notifications
You must be signed in to change notification settings - Fork 119
/
midi.js
73 lines (54 loc) · 1.46 KB
/
midi.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
var midi = require('bindings')('midi');
var Stream = require('stream');
// MIDI input inherits from EventEmitter
var EventEmitter = require('events').EventEmitter;
midi.Input.prototype.__proto__ = EventEmitter.prototype;
// Backwards compatibility.
midi.input = midi.Input;
midi.output = midi.Output;
module.exports = midi;
midi.createReadStream = function(input) {
input = input || new midi.Input();
var stream = new Stream();
stream.readable = true;
stream.paused = false;
stream.queue = [];
input.on('message', function(deltaTime, message) {
var packet = new Buffer.from(message);
if (!stream.paused) {
stream.emit('data', packet);
} else {
stream.queue.push(packet);
}
});
stream.pause = function() {
stream.paused = true;
};
stream.resume = function() {
stream.paused = false;
while (stream.queue.length && stream.emit('data', stream.queue.shift())) {}
};
return stream;
};
midi.createWriteStream = function(output) {
output = output || new midi.Output();
var stream = new Stream();
stream.writable = true;
stream.paused = false;
stream.queue = [];
stream.write = function(d) {
if (Buffer.isBuffer(d)) {
d = Array.prototype.slice.call(d, 0);
}
output.sendMessage(d);
return !this.paused;
}
stream.end = function(buf) {
buf && stream.write(buf);
stream.writable = false;
};
stream.destroy = function() {
stream.writable = false;
}
return stream;
};