Skip to content

Commit 9bbdfd0

Browse files
authored
Merge pull request #107 from grimmdude/support_end_track_event
Support manually adding EndTrackEvent with custom delta.
2 parents 42e817d + 963f23f commit 9bbdfd0

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

src/track.js

+17-4
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ class Track {
7979
event.buildData().events.forEach((e) => this.events.push(e));
8080
}
8181

82+
} else if (event instanceof EndTrackEvent) {
83+
// Only one EndTrackEvent is allowed, so remove
84+
// any existing ones before adding.
85+
this.removeEventsByType('end-track');
86+
this.events.push(event);
87+
8288
} else {
8389
this.events.push(event);
8490
}
@@ -93,9 +99,10 @@ class Track {
9399
* @return {Track}
94100
*/
95101
buildData(options = {}) {
96-
// Remove existing end track event and add one.
97-
// This makes sure it's at the very end of the event list.
98-
this.removeEventsByType('end-track').addEvent(new EndTrackEvent());
102+
// If the last event isn't EndTrackEvent, then tack it onto the data.
103+
if (!this.events.length || !(this.events[this.events.length - 1] instanceof EndTrackEvent)) {
104+
this.addEvent(new EndTrackEvent());
105+
}
99106

100107
// Reset
101108
this.data = [];
@@ -170,8 +177,14 @@ class Track {
170177
* @return {Track}
171178
*/
172179
mergeSingleEvent(event) {
180+
// There are no events yet, so just add it in.
181+
if (!this.events.length) {
182+
this.addEvent(event);
183+
return;
184+
}
185+
173186
// Find index of existing event we need to follow with
174-
var lastEventIndex = 0;
187+
let lastEventIndex;
175188

176189
for (let i = 0; i < this.events.length; i++) {
177190
if (this.events[i].tick > event.tick) break;

test/main.js

+12
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,18 @@ describe('MidiWriterJS', function() {
214214

215215
assert.equal(JSON.stringify(bar2note, null, 2), JSON.stringify(bar2note2, null, 2));
216216
})
217+
218+
it('should return specific base64 string when manually adding EndTrackEvent', function() {
219+
const track = new MidiWriter.Track();
220+
221+
track.addEvent([
222+
new MidiWriter.NoteEvent({pitch: ['C5', 'E5', 'G4'], duration: '4'}),
223+
new MidiWriter.EndTrackEvent({delta: 5000}),
224+
]);
225+
226+
const write = new MidiWriter.Writer(track);
227+
assert.equal('TVRoZAAAAAYAAAABAIBNVHJrAAAAHgCQSEAAkExAAJBDQIEAgEhAAIBMQACAQ0CnCP8vAA==', write.base64());
228+
})
217229
});
218230

219231
describe('#Utils()', function() {

0 commit comments

Comments
 (0)