@huffduff/midi-writer-ts 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/.editorconfig +24 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc.js +18 -0
  4. package/.nvmrc +1 -0
  5. package/.travis.yml +3 -0
  6. package/LICENSE +21 -0
  7. package/README.md +200 -0
  8. package/browser/midiwriter.js +1367 -0
  9. package/build/index.cjs +1219 -0
  10. package/build/index.mjs +1217 -0
  11. package/build/types/abstract-event.d.ts +7 -0
  12. package/build/types/chunks/chunk.d.ts +5 -0
  13. package/build/types/chunks/header.d.ts +13 -0
  14. package/build/types/chunks/track.d.ts +139 -0
  15. package/build/types/constants.d.ts +16 -0
  16. package/build/types/main.d.ts +56 -0
  17. package/build/types/meta-events/copyright-event.d.ts +18 -0
  18. package/build/types/meta-events/cue-point-event.d.ts +18 -0
  19. package/build/types/meta-events/end-track-event.d.ts +16 -0
  20. package/build/types/meta-events/instrument-name-event.d.ts +18 -0
  21. package/build/types/meta-events/key-signature-event.d.ts +13 -0
  22. package/build/types/meta-events/lyric-event.d.ts +18 -0
  23. package/build/types/meta-events/marker-event.d.ts +18 -0
  24. package/build/types/meta-events/meta-event.d.ts +5 -0
  25. package/build/types/meta-events/tempo-event.d.ts +20 -0
  26. package/build/types/meta-events/text-event.d.ts +18 -0
  27. package/build/types/meta-events/time-signature-event.d.ts +13 -0
  28. package/build/types/meta-events/track-name-event.d.ts +18 -0
  29. package/build/types/midi-events/controller-change-event.d.ts +22 -0
  30. package/build/types/midi-events/midi-event.d.ts +7 -0
  31. package/build/types/midi-events/note-event.d.ts +31 -0
  32. package/build/types/midi-events/note-off-event.d.ts +36 -0
  33. package/build/types/midi-events/note-on-event.d.ts +36 -0
  34. package/build/types/midi-events/pitch-bend-event.d.ts +17 -0
  35. package/build/types/midi-events/program-change-event.d.ts +20 -0
  36. package/build/types/utils.d.ts +105 -0
  37. package/build/types/vexflow.d.ts +30 -0
  38. package/build/types/writer.d.ts +45 -0
  39. package/examples/chopin-prelude-e-minor.js +143 -0
  40. package/examples/hot-cross-buns.js +24 -0
  41. package/examples/mauro.giuliani-op.47-main-theme.js +136 -0
  42. package/examples/notes-by-start-tick.js +45 -0
  43. package/examples/zelda-main-theme.js +435 -0
  44. package/jsdoc.json +5 -0
  45. package/package.json +79 -0
  46. package/postinstall.js +1 -0
  47. package/rollup.config.js +22 -0
  48. package/runkit.js +18 -0
  49. package/test/main.js +339 -0
  50. package/test/vexflow.js +165 -0
  51. package/test/writer.js +59 -0
  52. package/tsconfig.json +13 -0
  53. package/typedoc.json +5 -0
@@ -0,0 +1,1217 @@
1
+ import { toMidi } from '@tonaljs/midi';
2
+
3
+ /**
4
+ * MIDI file format constants.
5
+ * @return {Constants}
6
+ */
7
+ const Constants = {
8
+ VERSION: '3.1.1',
9
+ HEADER_CHUNK_TYPE: [0x4d, 0x54, 0x68, 0x64],
10
+ HEADER_CHUNK_LENGTH: [0x00, 0x00, 0x00, 0x06],
11
+ HEADER_CHUNK_FORMAT0: [0x00, 0x00],
12
+ HEADER_CHUNK_FORMAT1: [0x00, 0x01],
13
+ HEADER_CHUNK_DIVISION: [0x00, 0x80],
14
+ TRACK_CHUNK_TYPE: [0x4d, 0x54, 0x72, 0x6b],
15
+ META_EVENT_ID: 0xFF,
16
+ META_SMTPE_OFFSET: 0x54
17
+ };
18
+
19
+ /**
20
+ * Static utility functions used throughout the library.
21
+ */
22
+ class Utils {
23
+ /**
24
+ * Gets MidiWriterJS version number.
25
+ * @return {string}
26
+ */
27
+ static version() {
28
+ return Constants.VERSION;
29
+ }
30
+ /**
31
+ * Convert a string to an array of bytes
32
+ * @param {string} string
33
+ * @return {array}
34
+ */
35
+ static stringToBytes(string) {
36
+ return string.split('').map(char => char.charCodeAt(0));
37
+ }
38
+ /**
39
+ * Checks if argument is a valid number.
40
+ * @param {*} n - Value to check
41
+ * @return {boolean}
42
+ */
43
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
44
+ static isNumeric(n) {
45
+ return !isNaN(parseFloat(n)) && isFinite(n);
46
+ }
47
+ /**
48
+ * Returns the correct MIDI number for the specified pitch.
49
+ * Uses Tonal Midi - https://github.com/danigb/tonal/tree/master/packages/midi
50
+ * @param {(string|number)} pitch - 'C#4' or midi note code
51
+ * @param {string} middleC
52
+ * @return {number}
53
+ */
54
+ static getPitch(pitch, middleC = 'C4') {
55
+ return 60 - toMidi(middleC) + toMidi(pitch);
56
+ }
57
+ /**
58
+ * Translates number of ticks to MIDI timestamp format, returning an array of
59
+ * hex strings with the time values. Midi has a very particular time to express time,
60
+ * take a good look at the spec before ever touching this function.
61
+ * Thanks to https://github.com/sergi/jsmidi
62
+ *
63
+ * @param {number} ticks - Number of ticks to be translated
64
+ * @return {array} - Bytes that form the MIDI time value
65
+ */
66
+ static numberToVariableLength(ticks) {
67
+ ticks = Math.round(ticks);
68
+ let buffer = ticks & 0x7F;
69
+ // eslint-disable-next-line no-cond-assign
70
+ while (ticks = ticks >> 7) {
71
+ buffer <<= 8;
72
+ buffer |= ((ticks & 0x7F) | 0x80);
73
+ }
74
+ const bList = [];
75
+ // eslint-disable-next-line no-constant-condition
76
+ while (true) {
77
+ bList.push(buffer & 0xff);
78
+ if (buffer & 0x80)
79
+ buffer >>= 8;
80
+ else {
81
+ break;
82
+ }
83
+ }
84
+ return bList;
85
+ }
86
+ /**
87
+ * Counts number of bytes in string
88
+ * @param {string} s
89
+ * @return {number}
90
+ */
91
+ static stringByteCount(s) {
92
+ return encodeURI(s).split(/%..|./).length - 1;
93
+ }
94
+ /**
95
+ * Get an int from an array of bytes.
96
+ * @param {array} bytes
97
+ * @return {number}
98
+ */
99
+ static numberFromBytes(bytes) {
100
+ let hex = '';
101
+ let stringResult;
102
+ bytes.forEach((byte) => {
103
+ stringResult = byte.toString(16);
104
+ // ensure string is 2 chars
105
+ if (stringResult.length == 1)
106
+ stringResult = "0" + stringResult;
107
+ hex += stringResult;
108
+ });
109
+ return parseInt(hex, 16);
110
+ }
111
+ /**
112
+ * Takes a number and splits it up into an array of bytes. Can be padded by passing a number to bytesNeeded
113
+ * @param {number} number
114
+ * @param {number} bytesNeeded
115
+ * @return {array} - Array of bytes
116
+ */
117
+ static numberToBytes(number, bytesNeeded) {
118
+ bytesNeeded = bytesNeeded || 1;
119
+ let hexString = number.toString(16);
120
+ if (hexString.length & 1) { // Make sure hex string is even number of chars
121
+ hexString = '0' + hexString;
122
+ }
123
+ // Split hex string into an array of two char elements
124
+ const hexArray = hexString.match(/.{2}/g);
125
+ // Now parse them out as integers
126
+ const intArray = hexArray.map(item => parseInt(item, 16));
127
+ // Prepend empty bytes if we don't have enough
128
+ if (intArray.length < bytesNeeded) {
129
+ while (bytesNeeded - intArray.length > 0) {
130
+ intArray.unshift(0);
131
+ }
132
+ }
133
+ return intArray;
134
+ }
135
+ /**
136
+ * Converts value to array if needed.
137
+ * @param {any} value
138
+ * @return {array}
139
+ */
140
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
+ static toArray(value) {
142
+ if (Array.isArray(value))
143
+ return value;
144
+ return [value];
145
+ }
146
+ /**
147
+ * Converts velocity to value 0-127
148
+ * @param {number} velocity - Velocity value 1-100
149
+ * @return {number}
150
+ */
151
+ static convertVelocity(velocity) {
152
+ // Max passed value limited to 100
153
+ velocity = velocity > 100 ? 100 : velocity;
154
+ return Math.round(velocity / 100 * 127);
155
+ }
156
+ /**
157
+ * Gets the total number of ticks of a specified duration.
158
+ * Note: type=='note' defaults to quarter note, type==='rest' defaults to 0
159
+ * @param {(string|array)} duration
160
+ * @return {number}
161
+ */
162
+ static getTickDuration(duration) {
163
+ if (Array.isArray(duration)) {
164
+ // Recursively execute this method for each item in the array and return the sum of tick durations.
165
+ return duration.map((value) => {
166
+ return Utils.getTickDuration(value);
167
+ }).reduce((a, b) => {
168
+ return a + b;
169
+ }, 0);
170
+ }
171
+ duration = duration.toString();
172
+ if (duration.toLowerCase().charAt(0) === 't') {
173
+ // If duration starts with 't' then the number that follows is an explicit tick count
174
+ const ticks = parseInt(duration.substring(1));
175
+ if (isNaN(ticks) || ticks < 0) {
176
+ throw new Error(duration + ' is not a valid duration.');
177
+ }
178
+ return ticks;
179
+ }
180
+ // Need to apply duration here. Quarter note == Constants.HEADER_CHUNK_DIVISION
181
+ const quarterTicks = Utils.numberFromBytes(Constants.HEADER_CHUNK_DIVISION);
182
+ const tickDuration = quarterTicks * Utils.getDurationMultiplier(duration);
183
+ return Utils.getRoundedIfClose(tickDuration);
184
+ }
185
+ /**
186
+ * Due to rounding errors in JavaScript engines,
187
+ * it's safe to round when we're very close to the actual tick number
188
+ *
189
+ * @static
190
+ * @param {number} tick
191
+ * @return {number}
192
+ */
193
+ static getRoundedIfClose(tick) {
194
+ const roundedTick = Math.round(tick);
195
+ return Math.abs(roundedTick - tick) < 0.000001 ? roundedTick : tick;
196
+ }
197
+ /**
198
+ * Due to low precision of MIDI,
199
+ * we need to keep track of rounding errors in deltas.
200
+ * This function will calculate the rounding error for a given duration.
201
+ *
202
+ * @static
203
+ * @param {number} tick
204
+ * @return {number}
205
+ */
206
+ static getPrecisionLoss(tick) {
207
+ const roundedTick = Math.round(tick);
208
+ return roundedTick - tick;
209
+ }
210
+ /**
211
+ * Gets what to multiple ticks/quarter note by to get the specified duration.
212
+ * Note: type=='note' defaults to quarter note, type==='rest' defaults to 0
213
+ * @param {string} duration
214
+ * @return {number}
215
+ */
216
+ static getDurationMultiplier(duration) {
217
+ // Need to apply duration here.
218
+ // Quarter note == Constants.HEADER_CHUNK_DIVISION ticks.
219
+ if (duration === '0')
220
+ return 0;
221
+ const match = duration.match(/^(?<dotted>d+)?(?<base>\d+)(?:t(?<tuplet>\d*))?/);
222
+ if (match) {
223
+ const base = Number(match.groups.base);
224
+ // 1 or any power of two:
225
+ const isValidBase = base === 1 || ((base & (base - 1)) === 0);
226
+ if (isValidBase) {
227
+ // how much faster or slower is this note compared to a quarter?
228
+ const ratio = base / 4;
229
+ let durationInQuarters = 1 / ratio;
230
+ const { dotted, tuplet } = match.groups;
231
+ if (dotted) {
232
+ const thisManyDots = dotted.length;
233
+ const divisor = Math.pow(2, thisManyDots);
234
+ durationInQuarters = durationInQuarters + (durationInQuarters * ((divisor - 1) / divisor));
235
+ }
236
+ if (typeof tuplet === 'string') {
237
+ const fitInto = durationInQuarters * 2;
238
+ // default to triplet:
239
+ const thisManyNotes = Number(tuplet || '3');
240
+ durationInQuarters = fitInto / thisManyNotes;
241
+ }
242
+ return durationInQuarters;
243
+ }
244
+ }
245
+ throw new Error(duration + ' is not a valid duration.');
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Holds all data for a "controller change" MIDI event
251
+ * @param {object} fields {controllerNumber: integer, controllerValue: integer, delta: integer}
252
+ * @return {ControllerChangeEvent}
253
+ */
254
+ class ControllerChangeEvent {
255
+ constructor(fields) {
256
+ this.channel = fields.channel - 1 || 0;
257
+ this.controllerValue = fields.controllerValue;
258
+ this.controllerNumber = fields.controllerNumber;
259
+ this.delta = fields.delta || 0x00;
260
+ this.name = 'ControllerChangeEvent';
261
+ this.status = 0xB0;
262
+ this.data = Utils.numberToVariableLength(fields.delta).concat(this.status | this.channel, this.controllerNumber, this.controllerValue);
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Object representation of a tempo meta event.
268
+ * @param {object} fields {text: string, delta: integer}
269
+ * @return {CopyrightEvent}
270
+ */
271
+ class CopyrightEvent {
272
+ constructor(fields) {
273
+ this.delta = fields.delta || 0x00;
274
+ this.name = 'CopyrightEvent';
275
+ this.text = fields.text;
276
+ this.type = 0x02;
277
+ const textBytes = Utils.stringToBytes(this.text);
278
+ // Start with zero time delta
279
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
280
+ textBytes);
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Object representation of a cue point meta event.
286
+ * @param {object} fields {text: string, delta: integer}
287
+ * @return {CuePointEvent}
288
+ */
289
+ class CuePointEvent {
290
+ constructor(fields) {
291
+ this.delta = fields.delta || 0x00;
292
+ this.name = 'CuePointEvent';
293
+ this.text = fields.text;
294
+ this.type = 0x07;
295
+ const textBytes = Utils.stringToBytes(this.text);
296
+ // Start with zero time delta
297
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
298
+ textBytes);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Object representation of a end track meta event.
304
+ * @param {object} fields {delta: integer}
305
+ * @return {EndTrackEvent}
306
+ */
307
+ class EndTrackEvent {
308
+ constructor(fields) {
309
+ this.delta = (fields === null || fields === void 0 ? void 0 : fields.delta) || 0x00;
310
+ this.name = 'EndTrackEvent';
311
+ this.type = [0x2F, 0x00];
312
+ // Start with zero time delta
313
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Object representation of an instrument name meta event.
319
+ * @param {object} fields {text: string, delta: integer}
320
+ * @return {InstrumentNameEvent}
321
+ */
322
+ class InstrumentNameEvent {
323
+ constructor(fields) {
324
+ this.delta = fields.delta || 0x00;
325
+ this.name = 'InstrumentNameEvent';
326
+ this.text = fields.text;
327
+ this.type = 0x04;
328
+ const textBytes = Utils.stringToBytes(this.text);
329
+ // Start with zero time delta
330
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
331
+ textBytes);
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Object representation of a key signature meta event.
337
+ * @return {KeySignatureEvent}
338
+ */
339
+ class KeySignatureEvent {
340
+ constructor(sf, mi) {
341
+ this.name = 'KeySignatureEvent';
342
+ this.type = 0x59;
343
+ let mode = mi || 0;
344
+ sf = sf || 0;
345
+ // Function called with string notation
346
+ if (typeof mi === 'undefined') {
347
+ const fifths = [
348
+ ['Cb', 'Gb', 'Db', 'Ab', 'Eb', 'Bb', 'F', 'C', 'G', 'D', 'A', 'E', 'B', 'F#', 'C#'],
349
+ ['ab', 'eb', 'bb', 'f', 'c', 'g', 'd', 'a', 'e', 'b', 'f#', 'c#', 'g#', 'd#', 'a#']
350
+ ];
351
+ const _sflen = sf.length;
352
+ let note = sf || 'C';
353
+ if (sf[0] === sf[0].toLowerCase())
354
+ mode = 1;
355
+ if (_sflen > 1) {
356
+ switch (sf.charAt(_sflen - 1)) {
357
+ case 'm':
358
+ mode = 1;
359
+ note = sf.charAt(0).toLowerCase();
360
+ note = note.concat(sf.substring(1, _sflen - 1));
361
+ break;
362
+ case '-':
363
+ mode = 1;
364
+ note = sf.charAt(0).toLowerCase();
365
+ note = note.concat(sf.substring(1, _sflen - 1));
366
+ break;
367
+ case 'M':
368
+ mode = 0;
369
+ note = sf.charAt(0).toUpperCase();
370
+ note = note.concat(sf.substring(1, _sflen - 1));
371
+ break;
372
+ case '+':
373
+ mode = 0;
374
+ note = sf.charAt(0).toUpperCase();
375
+ note = note.concat(sf.substring(1, _sflen - 1));
376
+ break;
377
+ }
378
+ }
379
+ const fifthindex = fifths[mode].indexOf(note);
380
+ sf = fifthindex === -1 ? 0 : fifthindex - 7;
381
+ }
382
+ // Start with zero time delta
383
+ this.data = Utils.numberToVariableLength(0x00).concat(Constants.META_EVENT_ID, this.type, [0x02], // Size
384
+ Utils.numberToBytes(sf, 1), // Number of sharp or flats ( < 0 flat; > 0 sharp)
385
+ Utils.numberToBytes(mode, 1));
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Object representation of a lyric meta event.
391
+ * @param {object} fields {text: string, delta: integer}
392
+ * @return {LyricEvent}
393
+ */
394
+ class LyricEvent {
395
+ constructor(fields) {
396
+ this.delta = fields.delta || 0x00;
397
+ this.name = 'LyricEvent';
398
+ this.text = fields.text;
399
+ this.type = 0x05;
400
+ const textBytes = Utils.stringToBytes(this.text);
401
+ // Start with zero time delta
402
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
403
+ textBytes);
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Object representation of a marker meta event.
409
+ * @param {object} fields {text: string, delta: integer}
410
+ * @return {MarkerEvent}
411
+ */
412
+ class MarkerEvent {
413
+ constructor(fields) {
414
+ this.delta = fields.delta || 0x00;
415
+ this.name = 'MarkerEvent';
416
+ this.text = fields.text;
417
+ this.type = 0x06;
418
+ const textBytes = Utils.stringToBytes(this.text);
419
+ // Start with zero time delta
420
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
421
+ textBytes);
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Holds all data for a "note on" MIDI event
427
+ * @param {object} fields {data: []}
428
+ * @return {NoteOnEvent}
429
+ */
430
+ class NoteOnEvent {
431
+ constructor(fields) {
432
+ this.name = 'NoteOnEvent';
433
+ this.channel = fields.channel || 1;
434
+ this.pitch = fields.pitch;
435
+ this.wait = fields.wait || 0;
436
+ this.velocity = fields.velocity || 50;
437
+ this.tick = fields.tick || null;
438
+ this.delta = null;
439
+ this.data = fields.data;
440
+ this.status = 0x90;
441
+ }
442
+ /**
443
+ * Builds int array for this event.
444
+ * @param {Track} track - parent track
445
+ * @return {NoteOnEvent}
446
+ */
447
+ buildData(track, precisionDelta, options = {}) {
448
+ this.data = [];
449
+ // Explicitly defined startTick event
450
+ if (this.tick) {
451
+ this.tick = Utils.getRoundedIfClose(this.tick);
452
+ // If this is the first event in the track then use event's starting tick as delta.
453
+ if (track.tickPointer == 0) {
454
+ this.delta = this.tick;
455
+ }
456
+ }
457
+ else {
458
+ this.delta = Utils.getTickDuration(this.wait);
459
+ this.tick = Utils.getRoundedIfClose(track.tickPointer + this.delta);
460
+ }
461
+ this.deltaWithPrecisionCorrection = Utils.getRoundedIfClose(this.delta - precisionDelta);
462
+ this.data = Utils.numberToVariableLength(this.deltaWithPrecisionCorrection)
463
+ .concat(this.status | this.channel - 1, Utils.getPitch(this.pitch, options.middleC), Utils.convertVelocity(this.velocity));
464
+ return this;
465
+ }
466
+ }
467
+
468
+ /**
469
+ * Holds all data for a "note off" MIDI event
470
+ * @param {object} fields {data: []}
471
+ * @return {NoteOffEvent}
472
+ */
473
+ class NoteOffEvent {
474
+ constructor(fields) {
475
+ this.name = 'NoteOffEvent';
476
+ this.channel = fields.channel || 1;
477
+ this.pitch = fields.pitch;
478
+ this.velocity = fields.velocity || 50;
479
+ this.tick = fields.tick || null;
480
+ this.data = fields.data;
481
+ this.delta = fields.delta || Utils.getTickDuration(fields.duration);
482
+ this.status = 0x80;
483
+ }
484
+ /**
485
+ * Builds int array for this event.
486
+ * @param {Track} track - parent track
487
+ * @return {NoteOffEvent}
488
+ */
489
+ buildData(track, precisionDelta, options = {}) {
490
+ if (this.tick === null) {
491
+ this.tick = Utils.getRoundedIfClose(this.delta + track.tickPointer);
492
+ }
493
+ this.deltaWithPrecisionCorrection = Utils.getRoundedIfClose(this.delta - precisionDelta);
494
+ this.data = Utils.numberToVariableLength(this.deltaWithPrecisionCorrection)
495
+ .concat(this.status | this.channel - 1, Utils.getPitch(this.pitch, options.middleC), Utils.convertVelocity(this.velocity));
496
+ return this;
497
+ }
498
+ }
499
+
500
+ /**
501
+ * Wrapper for noteOnEvent/noteOffEvent objects that builds both events.
502
+ * @param {object} fields - {pitch: '[C4]', duration: '4', wait: '4', velocity: 1-100}
503
+ * @return {NoteEvent}
504
+ */
505
+ class NoteEvent {
506
+ constructor(fields) {
507
+ this.data = [];
508
+ this.name = 'NoteEvent';
509
+ this.pitch = Utils.toArray(fields.pitch);
510
+ this.channel = fields.channel || 1;
511
+ this.duration = fields.duration || '4';
512
+ this.grace = fields.grace;
513
+ this.repeat = fields.repeat || 1;
514
+ this.sequential = fields.sequential || false;
515
+ this.tick = fields.startTick || fields.tick || null;
516
+ this.velocity = fields.velocity || 50;
517
+ this.wait = fields.wait || 0;
518
+ this.tickDuration = Utils.getTickDuration(this.duration);
519
+ this.restDuration = Utils.getTickDuration(this.wait);
520
+ this.events = []; // Hold actual NoteOn/NoteOff events
521
+ }
522
+ /**
523
+ * Builds int array for this event.
524
+ * @return {NoteEvent}
525
+ */
526
+ buildData() {
527
+ // Reset data array
528
+ this.data = [];
529
+ // Apply grace note(s) and subtract ticks (currently 1 tick per grace note) from tickDuration so net value is the same
530
+ if (this.grace) {
531
+ const graceDuration = 1;
532
+ this.grace = Utils.toArray(this.grace);
533
+ this.grace.forEach(() => {
534
+ const noteEvent = new NoteEvent({ pitch: this.grace, duration: 'T' + graceDuration });
535
+ this.data = this.data.concat(noteEvent.data);
536
+ });
537
+ }
538
+ // fields.pitch could be an array of pitches.
539
+ // If so create note events for each and apply the same duration.
540
+ // By default this is a chord if it's an array of notes that requires one NoteOnEvent.
541
+ // If this.sequential === true then it's a sequential string of notes that requires separate NoteOnEvents.
542
+ if (!this.sequential) {
543
+ // Handle repeat
544
+ for (let j = 0; j < this.repeat; j++) {
545
+ // Note on
546
+ this.pitch.forEach((p, i) => {
547
+ let noteOnNew;
548
+ if (i == 0) {
549
+ noteOnNew = new NoteOnEvent({
550
+ channel: this.channel,
551
+ wait: this.wait,
552
+ delta: Utils.getTickDuration(this.wait),
553
+ velocity: this.velocity,
554
+ pitch: p,
555
+ tick: this.tick,
556
+ });
557
+ }
558
+ else {
559
+ // Running status (can ommit the note on status)
560
+ //noteOn = new NoteOnEvent({data: [0, Utils.getPitch(p), Utils.convertVelocity(this.velocity)]});
561
+ noteOnNew = new NoteOnEvent({
562
+ channel: this.channel,
563
+ wait: 0,
564
+ delta: 0,
565
+ velocity: this.velocity,
566
+ pitch: p,
567
+ tick: this.tick,
568
+ });
569
+ }
570
+ this.events.push(noteOnNew);
571
+ });
572
+ // Note off
573
+ this.pitch.forEach((p, i) => {
574
+ let noteOffNew;
575
+ if (i == 0) {
576
+ //noteOff = new NoteOffEvent({data: Utils.numberToVariableLength(tickDuration).concat(this.getNoteOffStatus(), Utils.getPitch(p), Utils.convertVelocity(this.velocity))});
577
+ noteOffNew = new NoteOffEvent({
578
+ channel: this.channel,
579
+ duration: this.duration,
580
+ velocity: this.velocity,
581
+ pitch: p,
582
+ tick: this.tick !== null ? Utils.getTickDuration(this.duration) + this.tick : null,
583
+ });
584
+ }
585
+ else {
586
+ // Running status (can omit the note off status)
587
+ //noteOff = new NoteOffEvent({data: [0, Utils.getPitch(p), Utils.convertVelocity(this.velocity)]});
588
+ noteOffNew = new NoteOffEvent({
589
+ channel: this.channel,
590
+ duration: 0,
591
+ velocity: this.velocity,
592
+ pitch: p,
593
+ tick: this.tick !== null ? Utils.getTickDuration(this.duration) + this.tick : null,
594
+ });
595
+ }
596
+ this.events.push(noteOffNew);
597
+ });
598
+ }
599
+ }
600
+ else {
601
+ // Handle repeat
602
+ for (let j = 0; j < this.repeat; j++) {
603
+ this.pitch.forEach((p, i) => {
604
+ const noteOnNew = new NoteOnEvent({
605
+ channel: this.channel,
606
+ wait: (i > 0 ? 0 : this.wait),
607
+ delta: (i > 0 ? 0 : Utils.getTickDuration(this.wait)),
608
+ velocity: this.velocity,
609
+ pitch: p,
610
+ tick: this.tick,
611
+ });
612
+ const noteOffNew = new NoteOffEvent({
613
+ channel: this.channel,
614
+ duration: this.duration,
615
+ velocity: this.velocity,
616
+ pitch: p,
617
+ });
618
+ this.events.push(noteOnNew, noteOffNew);
619
+ });
620
+ }
621
+ }
622
+ return this;
623
+ }
624
+ }
625
+
626
+ /**
627
+ * Holds all data for a "Pitch Bend" MIDI event
628
+ * [ -1.0, 0, 1.0 ] -> [ 0, 8192, 16383]
629
+ * @param {object} fields { bend : float, channel : int, delta: int }
630
+ * @return {PitchBendEvent}
631
+ */
632
+ class PitchBendEvent {
633
+ constructor(fields) {
634
+ this.channel = fields.channel || 0;
635
+ this.delta = fields.delta || 0x00;
636
+ this.name = 'PitchBendEvent';
637
+ this.status = 0xE0;
638
+ const bend14 = this.scale14bits(fields.bend);
639
+ const lsbValue = bend14 & 0x7f;
640
+ const msbValue = (bend14 >> 7) & 0x7f;
641
+ this.data = Utils.numberToVariableLength(this.delta).concat(this.status | this.channel, lsbValue, msbValue);
642
+ }
643
+ scale14bits(zeroOne) {
644
+ if (zeroOne <= 0) {
645
+ return Math.floor(16384 * (zeroOne + 1) / 2);
646
+ }
647
+ return Math.floor(16383 * (zeroOne + 1) / 2);
648
+ }
649
+ }
650
+
651
+ /**
652
+ * Holds all data for a "program change" MIDI event
653
+ * @param {object} fields {instrument: integer, delta: integer}
654
+ * @return {ProgramChangeEvent}
655
+ */
656
+ class ProgramChangeEvent {
657
+ constructor(fields) {
658
+ this.channel = fields.channel || 0;
659
+ this.delta = fields.delta || 0x00;
660
+ this.instrument = fields.instrument;
661
+ this.status = 0xC0;
662
+ this.name = 'ProgramChangeEvent';
663
+ // delta time defaults to 0.
664
+ this.data = Utils.numberToVariableLength(this.delta).concat(this.status | this.channel, this.instrument);
665
+ }
666
+ }
667
+
668
+ /**
669
+ * Object representation of a tempo meta event.
670
+ * @param {object} fields {bpm: integer, delta: integer}
671
+ * @return {TempoEvent}
672
+ */
673
+ class TempoEvent {
674
+ constructor(fields) {
675
+ this.bpm = fields.bpm;
676
+ this.delta = fields.delta || 0x00;
677
+ this.tick = fields.tick;
678
+ this.name = 'TempoEvent';
679
+ this.type = 0x51;
680
+ const tempo = Math.round(60000000 / this.bpm);
681
+ // Start with zero time delta
682
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, [0x03], // Size
683
+ Utils.numberToBytes(tempo, 3));
684
+ }
685
+ }
686
+
687
+ /**
688
+ * Object representation of a tempo meta event.
689
+ * @param {object} fields {text: string, delta: integer}
690
+ * @return {TextEvent}
691
+ */
692
+ class TextEvent {
693
+ constructor(fields) {
694
+ this.delta = fields.delta || 0x00;
695
+ this.text = fields.text;
696
+ this.name = 'TextEvent';
697
+ this.type = 0x01;
698
+ const textBytes = Utils.stringToBytes(this.text);
699
+ // Start with zero time delta
700
+ this.data = Utils.numberToVariableLength(fields.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
701
+ textBytes);
702
+ }
703
+ }
704
+
705
+ /**
706
+ * Object representation of a time signature meta event.
707
+ * @return {TimeSignatureEvent}
708
+ */
709
+ class TimeSignatureEvent {
710
+ constructor(numerator, denominator, midiclockspertick, notespermidiclock) {
711
+ this.name = 'TimeSignatureEvent';
712
+ this.type = 0x58;
713
+ // Start with zero time delta
714
+ this.data = Utils.numberToVariableLength(0x00).concat(Constants.META_EVENT_ID, this.type, [0x04], // Size
715
+ Utils.numberToBytes(numerator, 1), // Numerator, 1 bytes
716
+ Utils.numberToBytes(Math.log2(denominator), 1), // Denominator is expressed as pow of 2, 1 bytes
717
+ Utils.numberToBytes(midiclockspertick || 24, 1), // MIDI Clocks per tick, 1 bytes
718
+ Utils.numberToBytes(notespermidiclock || 8, 1));
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Object representation of a tempo meta event.
724
+ * @param {object} fields {text: string, delta: integer}
725
+ * @return {TrackNameEvent}
726
+ */
727
+ class TrackNameEvent {
728
+ constructor(fields) {
729
+ this.delta = fields.delta || 0x00;
730
+ this.name = 'TrackNameEvent';
731
+ this.text = fields.text;
732
+ this.type = 0x03;
733
+ const textBytes = Utils.stringToBytes(this.text);
734
+ // Start with zero time delta
735
+ this.data = Utils.numberToVariableLength(this.delta).concat(Constants.META_EVENT_ID, this.type, Utils.numberToVariableLength(textBytes.length), // Size
736
+ textBytes);
737
+ }
738
+ }
739
+
740
+ /**
741
+ * Holds all data for a track.
742
+ * @param {object} fields {type: number, data: array, size: array, events: array}
743
+ * @return {Track}
744
+ */
745
+ class Track {
746
+ constructor() {
747
+ this.type = Constants.TRACK_CHUNK_TYPE;
748
+ this.data = [];
749
+ this.size = [];
750
+ this.events = [];
751
+ this.explicitTickEvents = [];
752
+ // If there are any events with an explicit tick defined then we will create a "sub" track for those
753
+ // and merge them in and the end.
754
+ this.tickPointer = 0; // Each time an event is added this will increase
755
+ }
756
+ /**
757
+ * Adds any event type to the track.
758
+ * Events without a specific startTick property are assumed to be added in order of how they should output.
759
+ * Events with a specific startTick property are set aside for now will be merged in during build process.
760
+ *
761
+ * TODO: Don't put startTick events in their own array. Just lump everything together and sort it out during buildData();
762
+ * @param {(NoteEvent|ProgramChangeEvent)} events - Event object or array of Event objects.
763
+ * @param {Function} mapFunction - Callback which can be used to apply specific properties to all events.
764
+ * @return {Track}
765
+ */
766
+ addEvent(events, mapFunction) {
767
+ Utils.toArray(events).forEach((event, i) => {
768
+ if (event instanceof NoteEvent) {
769
+ // Handle map function if provided
770
+ if (typeof mapFunction === 'function') {
771
+ const properties = mapFunction(i, event);
772
+ if (typeof properties === 'object') {
773
+ Object.assign(event, properties);
774
+ }
775
+ }
776
+ // If this note event has an explicit startTick then we need to set aside for now
777
+ if (event.tick !== null) {
778
+ this.explicitTickEvents.push(event);
779
+ }
780
+ else {
781
+ // Push each on/off event to track's event stack
782
+ event.buildData().events.forEach((e) => this.events.push(e));
783
+ }
784
+ }
785
+ else {
786
+ this.events.push(event);
787
+ }
788
+ });
789
+ return this;
790
+ }
791
+ /**
792
+ * Builds int array of all events.
793
+ * @param {object} options
794
+ * @return {Track}
795
+ */
796
+ buildData(options = {}) {
797
+ // Reset
798
+ this.data = [];
799
+ this.size = [];
800
+ this.tickPointer = 0;
801
+ let precisionLoss = 0;
802
+ this.events.forEach((event) => {
803
+ // Build event & add to total tick duration
804
+ if (event instanceof NoteOnEvent || event instanceof NoteOffEvent) {
805
+ const built = event.buildData(this, precisionLoss, options);
806
+ precisionLoss = Utils.getPrecisionLoss(event.deltaWithPrecisionCorrection || 0);
807
+ this.data = this.data.concat(built.data);
808
+ this.tickPointer = Utils.getRoundedIfClose(event.tick);
809
+ }
810
+ else if (event instanceof TempoEvent) {
811
+ this.tickPointer = Utils.getRoundedIfClose(event.tick);
812
+ this.data = this.data.concat(event.data);
813
+ }
814
+ else {
815
+ this.data = this.data.concat(event.data);
816
+ }
817
+ });
818
+ this.mergeExplicitTickEvents();
819
+ // If the last event isn't EndTrackEvent, then tack it onto the data.
820
+ if (!this.events.length || !(this.events[this.events.length - 1] instanceof EndTrackEvent)) {
821
+ this.data = this.data.concat((new EndTrackEvent).data);
822
+ }
823
+ this.size = Utils.numberToBytes(this.data.length, 4); // 4 bytes long
824
+ return this;
825
+ }
826
+ mergeExplicitTickEvents() {
827
+ if (!this.explicitTickEvents.length)
828
+ return;
829
+ // First sort asc list of events by startTick
830
+ this.explicitTickEvents.sort((a, b) => a.tick - b.tick);
831
+ // Now this.explicitTickEvents is in correct order, and so is this.events naturally.
832
+ // For each explicit tick event, splice it into the main list of events and
833
+ // adjust the delta on the following events so they still play normally.
834
+ this.explicitTickEvents.forEach((noteEvent) => {
835
+ // Convert NoteEvent to it's respective NoteOn/NoteOff events
836
+ // Note that as we splice in events the delta for the NoteOff ones will
837
+ // Need to change based on what comes before them after the splice.
838
+ noteEvent.buildData().events.forEach((e) => e.buildData(this));
839
+ // Merge each event individually into this track's event list.
840
+ noteEvent.events.forEach((event) => this.mergeSingleEvent(event));
841
+ });
842
+ // Hacky way to rebuild track with newly spliced events. Need better solution.
843
+ this.explicitTickEvents = [];
844
+ this.buildData();
845
+ }
846
+ /**
847
+ * Merges another track's events with this track.
848
+ * @param {Track} track
849
+ * @return {Track}
850
+ */
851
+ mergeTrack(track) {
852
+ // First build this track to populate each event's tick property
853
+ this.buildData();
854
+ // Then build track to be merged so that tick property is populated on all events & merge each event.
855
+ track.buildData().events.forEach((event) => this.mergeSingleEvent(event));
856
+ return this;
857
+ }
858
+ /**
859
+ * Merges a single event into this track's list of events based on event.tick property.
860
+ * @param {AbstractEvent} - event
861
+ * @return {Track}
862
+ */
863
+ mergeSingleEvent(event) {
864
+ // There are no events yet, so just add it in.
865
+ if (!this.events.length) {
866
+ this.addEvent(event);
867
+ return;
868
+ }
869
+ // Find index of existing event we need to follow with
870
+ let lastEventIndex;
871
+ for (let i = 0; i < this.events.length; i++) {
872
+ if (this.events[i].tick > event.tick)
873
+ break;
874
+ lastEventIndex = i;
875
+ }
876
+ const splicedEventIndex = lastEventIndex + 1;
877
+ // Need to adjust the delta of this event to ensure it falls on the correct tick.
878
+ event.delta = event.tick - this.events[lastEventIndex].tick;
879
+ // Splice this event at lastEventIndex + 1
880
+ this.events.splice(splicedEventIndex, 0, event);
881
+ // Now adjust delta of all following events
882
+ for (let i = splicedEventIndex + 1; i < this.events.length; i++) {
883
+ // Since each existing event should have a tick value at this point we just need to
884
+ // adjust delta to that the event still falls on the correct tick.
885
+ this.events[i].delta = this.events[i].tick - this.events[i - 1].tick;
886
+ }
887
+ }
888
+ /**
889
+ * Removes all events matching specified type.
890
+ * @param {string} eventName - Event type
891
+ * @return {Track}
892
+ */
893
+ removeEventsByName(eventName) {
894
+ this.events.forEach((event, index) => {
895
+ if (event.name === eventName) {
896
+ this.events.splice(index, 1);
897
+ }
898
+ });
899
+ return this;
900
+ }
901
+ /**
902
+ * Sets tempo of the MIDI file.
903
+ * @param {number} bpm - Tempo in beats per minute.
904
+ * @param {number} tick - Start tick.
905
+ * @return {Track}
906
+ */
907
+ setTempo(bpm, tick = 0) {
908
+ return this.addEvent(new TempoEvent({ bpm, tick }));
909
+ }
910
+ /**
911
+ * Sets time signature.
912
+ * @param {number} numerator - Top number of the time signature.
913
+ * @param {number} denominator - Bottom number of the time signature.
914
+ * @param {number} midiclockspertick - Defaults to 24.
915
+ * @param {number} notespermidiclock - Defaults to 8.
916
+ * @return {Track}
917
+ */
918
+ setTimeSignature(numerator, denominator, midiclockspertick, notespermidiclock) {
919
+ return this.addEvent(new TimeSignatureEvent(numerator, denominator, midiclockspertick, notespermidiclock));
920
+ }
921
+ /**
922
+ * Sets key signature.
923
+ * @param {*} sf -
924
+ * @param {*} mi -
925
+ * @return {Track}
926
+ */
927
+ setKeySignature(sf, mi) {
928
+ return this.addEvent(new KeySignatureEvent(sf, mi));
929
+ }
930
+ /**
931
+ * Adds text to MIDI file.
932
+ * @param {string} text - Text to add.
933
+ * @return {Track}
934
+ */
935
+ addText(text) {
936
+ return this.addEvent(new TextEvent({ text }));
937
+ }
938
+ /**
939
+ * Adds copyright to MIDI file.
940
+ * @param {string} text - Text of copyright line.
941
+ * @return {Track}
942
+ */
943
+ addCopyright(text) {
944
+ return this.addEvent(new CopyrightEvent({ text }));
945
+ }
946
+ /**
947
+ * Adds Sequence/Track Name.
948
+ * @param {string} text - Text of track name.
949
+ * @return {Track}
950
+ */
951
+ addTrackName(text) {
952
+ return this.addEvent(new TrackNameEvent({ text }));
953
+ }
954
+ /**
955
+ * Sets instrument name of track.
956
+ * @param {string} text - Name of instrument.
957
+ * @return {Track}
958
+ */
959
+ addInstrumentName(text) {
960
+ return this.addEvent(new InstrumentNameEvent({ text }));
961
+ }
962
+ /**
963
+ * Adds marker to MIDI file.
964
+ * @param {string} text - Marker text.
965
+ * @return {Track}
966
+ */
967
+ addMarker(text) {
968
+ return this.addEvent(new MarkerEvent({ text }));
969
+ }
970
+ /**
971
+ * Adds cue point to MIDI file.
972
+ * @param {string} text - Text of cue point.
973
+ * @return {Track}
974
+ */
975
+ addCuePoint(text) {
976
+ return this.addEvent(new CuePointEvent({ text }));
977
+ }
978
+ /**
979
+ * Adds lyric to MIDI file.
980
+ * @param {string} text - Lyric text to add.
981
+ * @return {Track}
982
+ */
983
+ addLyric(text) {
984
+ return this.addEvent(new LyricEvent({ text }));
985
+ }
986
+ /**
987
+ * Channel mode messages
988
+ * @return {Track}
989
+ */
990
+ polyModeOn() {
991
+ const event = new NoteOnEvent({ data: [0x00, 0xB0, 0x7E, 0x00] });
992
+ return this.addEvent(event);
993
+ }
994
+ /**
995
+ * Sets a pitch bend.
996
+ * @param {float} bend - Bend value ranging [-1,1], zero meaning no bend.
997
+ * @return {Track}
998
+ */
999
+ setPitchBend(bend) {
1000
+ return this.addEvent(new PitchBendEvent({ bend }));
1001
+ }
1002
+ /**
1003
+ * Adds a controller change event
1004
+ * @param {number} number - Control number.
1005
+ * @param {number} value - Control value.
1006
+ * @param {number} channel - Channel to send controller change event on (1-based).
1007
+ * @param {number} delta - Track tick offset for cc event.
1008
+ * @return {Track}
1009
+ */
1010
+ controllerChange(number, value, channel, delta) {
1011
+ return this.addEvent(new ControllerChangeEvent({ controllerNumber: number, controllerValue: value, channel: channel, delta: delta }));
1012
+ }
1013
+ }
1014
+
1015
+ class VexFlow {
1016
+ /**
1017
+ * Support for converting VexFlow voice into MidiWriterJS track
1018
+ * @return MidiWriter.Track object
1019
+ */
1020
+ trackFromVoice(voice, options = { addRenderedAccidentals: false }) {
1021
+ const track = new Track;
1022
+ let wait = [];
1023
+ voice.tickables.forEach(tickable => {
1024
+ if (tickable.noteType === 'n') {
1025
+ track.addEvent(new NoteEvent({
1026
+ pitch: tickable.keys.map((pitch, index) => this.convertPitch(pitch, index, tickable, options.addRenderedAccidentals)),
1027
+ duration: this.convertDuration(tickable),
1028
+ wait
1029
+ }));
1030
+ // reset wait
1031
+ wait = [];
1032
+ }
1033
+ else if (tickable.noteType === 'r') {
1034
+ // move on to the next tickable and add this to the stack
1035
+ // of the `wait` property for the next note event
1036
+ wait.push(this.convertDuration(tickable));
1037
+ }
1038
+ });
1039
+ // There may be outstanding rests at the end of the track,
1040
+ // pad with a ghost note (zero duration and velocity), just to capture the wait.
1041
+ if (wait.length > 0) {
1042
+ track.addEvent(new NoteEvent({ pitch: '[c4]', duration: '0', wait, velocity: '0' }));
1043
+ }
1044
+ return track;
1045
+ }
1046
+ /**
1047
+ * Converts VexFlow pitch syntax to MidiWriterJS syntax
1048
+ * @param pitch string
1049
+ * @param index pitch index
1050
+ * @param note struct from Vexflow
1051
+ * @param addRenderedAccidentals adds Vexflow rendered accidentals
1052
+ */
1053
+ convertPitch(pitch, index, note, addRenderedAccidentals = false) {
1054
+ var _a;
1055
+ // Splits note name from octave
1056
+ const pitchParts = pitch.split('/');
1057
+ // Retrieves accidentals from pitch
1058
+ // Removes natural accidentals since they are not accepted in Tonal Midi
1059
+ let accidentals = pitchParts[0].substring(1).replace('n', '');
1060
+ if (addRenderedAccidentals) {
1061
+ (_a = note.getAccidentals()) === null || _a === void 0 ? void 0 : _a.forEach(accidental => {
1062
+ if (accidental.index === index) {
1063
+ if (accidental.type === 'n') {
1064
+ accidentals = '';
1065
+ }
1066
+ else {
1067
+ accidentals += accidental.type;
1068
+ }
1069
+ }
1070
+ });
1071
+ }
1072
+ return pitchParts[0][0] + accidentals + pitchParts[1];
1073
+ }
1074
+ /**
1075
+ * Converts VexFlow duration syntax to MidiWriterJS syntax
1076
+ * @param note struct from VexFlow
1077
+ */
1078
+ convertDuration(note) {
1079
+ return 'd'.repeat(note.dots) + this.convertBaseDuration(note.duration) + (note.tuplet ? 't' + note.tuplet.num_notes : '');
1080
+ }
1081
+ /**
1082
+ * Converts VexFlow base duration syntax to MidiWriterJS syntax
1083
+ * @param duration Vexflow duration
1084
+ * @returns MidiWriterJS duration
1085
+ */
1086
+ convertBaseDuration(duration) {
1087
+ switch (duration) {
1088
+ case 'w':
1089
+ return '1';
1090
+ case 'h':
1091
+ return '2';
1092
+ case 'q':
1093
+ return '4';
1094
+ default:
1095
+ return duration;
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ /**
1101
+ * Object representation of a header chunk section of a MIDI file.
1102
+ * @param {number} numberOfTracks - Number of tracks
1103
+ * @return {Header}
1104
+ */
1105
+ class Header {
1106
+ constructor(numberOfTracks) {
1107
+ this.type = Constants.HEADER_CHUNK_TYPE;
1108
+ const trackType = numberOfTracks > 1 ? Constants.HEADER_CHUNK_FORMAT1 : Constants.HEADER_CHUNK_FORMAT0;
1109
+ this.data = trackType.concat(Utils.numberToBytes(numberOfTracks, 2), // two bytes long,
1110
+ Constants.HEADER_CHUNK_DIVISION);
1111
+ this.size = [0, 0, 0, this.data.length];
1112
+ }
1113
+ }
1114
+
1115
+ /**
1116
+ * Object that puts together tracks and provides methods for file output.
1117
+ * @param {array|Track} tracks - A single {Track} object or an array of {Track} objects.
1118
+ * @param {object} options - {middleC: 'C4'}
1119
+ * @return {Writer}
1120
+ */
1121
+ class Writer {
1122
+ constructor(tracks, options = {}) {
1123
+ // Ensure tracks is an array
1124
+ this.tracks = Utils.toArray(tracks);
1125
+ this.options = options;
1126
+ }
1127
+ /**
1128
+ * Builds array of data from chunkschunks.
1129
+ * @return {array}
1130
+ */
1131
+ buildData() {
1132
+ const data = [];
1133
+ data.push(new Header(this.tracks.length));
1134
+ // For each track add final end of track event and build data
1135
+ this.tracks.forEach((track) => {
1136
+ data.push(track.buildData(this.options));
1137
+ });
1138
+ return data;
1139
+ }
1140
+ /**
1141
+ * Builds the file into a Uint8Array
1142
+ * @return {Uint8Array}
1143
+ */
1144
+ buildFile() {
1145
+ let build = [];
1146
+ // Data consists of chunks which consists of data
1147
+ this.buildData().forEach((d) => build = build.concat(d.type, d.size, d.data));
1148
+ return new Uint8Array(build);
1149
+ }
1150
+ /**
1151
+ * Convert file buffer to a base64 string. Different methods depending on if browser or node.
1152
+ * @return {string}
1153
+ */
1154
+ base64() {
1155
+ if (typeof btoa === 'function') {
1156
+ let binary = '';
1157
+ const bytes = this.buildFile();
1158
+ const len = bytes.byteLength;
1159
+ for (let i = 0; i < len; i++) {
1160
+ binary += String.fromCharCode(bytes[i]);
1161
+ }
1162
+ return btoa(binary);
1163
+ }
1164
+ return Buffer.from(this.buildFile()).toString('base64');
1165
+ }
1166
+ /**
1167
+ * Get the data URI.
1168
+ * @return {string}
1169
+ */
1170
+ dataUri() {
1171
+ return 'data:audio/midi;base64,' + this.base64();
1172
+ }
1173
+ /**
1174
+ * Set option on instantiated Writer.
1175
+ * @param {string} key
1176
+ * @param {any} value
1177
+ * @return {Writer}
1178
+ */
1179
+ setOption(key, value) {
1180
+ this.options[key] = value;
1181
+ return this;
1182
+ }
1183
+ /**
1184
+ * Output to stdout
1185
+ * @return {string}
1186
+ */
1187
+ stdout() {
1188
+ return process.stdout.write(Buffer.from(this.buildFile()));
1189
+ }
1190
+ }
1191
+
1192
+ var main = {
1193
+ Constants,
1194
+ ControllerChangeEvent,
1195
+ CopyrightEvent,
1196
+ CuePointEvent,
1197
+ EndTrackEvent,
1198
+ InstrumentNameEvent,
1199
+ KeySignatureEvent,
1200
+ LyricEvent,
1201
+ MarkerEvent,
1202
+ NoteOnEvent,
1203
+ NoteOffEvent,
1204
+ NoteEvent,
1205
+ PitchBendEvent,
1206
+ ProgramChangeEvent,
1207
+ TempoEvent,
1208
+ TextEvent,
1209
+ TimeSignatureEvent,
1210
+ Track,
1211
+ TrackNameEvent,
1212
+ Utils,
1213
+ VexFlow,
1214
+ Writer
1215
+ };
1216
+
1217
+ export { main as default };