-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusicStructure.pde
More file actions
421 lines (347 loc) · 12.1 KB
/
Copy pathmusicStructure.pde
File metadata and controls
421 lines (347 loc) · 12.1 KB
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
float MUSIC_EPSILON = 0.001;
//Parent clas for anything that can go inside a measure
class MusicEvent{
float duration; //0.25 is sixteenth, 0.5 is eigth, 1.0 is quarter, 2.0 is half, 4.0 is whole
//Given that the bpm is x, we have x/60 beats per second.
MusicEvent(float d){
this.duration = d;
}
boolean isRest(){
return this instanceof Rest;
}
}
class Note extends MusicEvent{
int midiNote;
Instrument family;
boolean hasAccidental;
int accidentalModifier; //-1 is flat, 0 is natural, 1 is sharp
Note(float d, int note, Instrument i){
super(d);
this.midiNote = note;
this.family = i;
this.hasAccidental = false;
this.accidentalModifier = 0;
}
void play(){
this.family.playNote(this.midiNote, this.duration);
}
}
class Rest extends MusicEvent{
Rest(float d){
super(d);
}
}
//A measure holds all the notes/rests for one track at one spot in the song
class Measure{
int track, id, bpm; //What track this belongs to, the id is the index within the track
TimeSignature timeSig;
ArrayList<MusicEvent> events; //Everyihtng that happens in this measure (notes, rests, e.t.c)
//I keep this as an arraylist to keep general processing simple, but in theory the max length of htis list is set (based on the time signature)
HashMap<Integer, Integer> withinMeasureAccidentals = new HashMap<Integer, Integer>();
Measure(int track, int id, TimeSignature timeSig){ //id is the index of the measure within the MusicalPiece class for that specific track
this.track = track;
this.id = id;
this.timeSig = timeSig;
this.events = new ArrayList<MusicEvent>();
for (int i=0;i<this.timeSig.beatsPerMeasure();i++){
//Intialize it with the proper rests for this time signature
Rest r = new Rest(this.timeSig.beatDuration());
this.events.add(r);
}
this.withinMeasureAccidentals = new HashMap<Integer, Integer>();
}
float beatUsed(){
float total = 0;
for (MusicEvent e: events){
total += e.duration;
}
return total;
}
float beatsRemaining(){
return timeSig.measureDuration() - beatUsed();
}
float restDuration(){
float total = 0;
for (MusicEvent e: events){
if (e instanceof Rest){
total += e.duration;
}
}
return total;
}
//Main editing method. It replaces events while keeping the measure length right
boolean changeEvent(MusicEvent e, int i){
//This method updates the events list, subdividing or eating rests as needed
MusicEvent oldEvent = this.events.get(i);
if (abs(e.duration-oldEvent.duration) < MUSIC_EPSILON){
//If duration matches no subdividing is needed, can directly replace
this.events.set(i, e);
return true;
}else if(e.duration < oldEvent.duration){
//This means we have to add more rests to subdivide
int mult = int(oldEvent.duration / e.duration); //How many times the new note can fit into the old note
float leftover = oldEvent.duration - e.duration*mult;
//mult tells us how to subdivide this
this.events.set(i, e);//First replace this note and then add mult-1 rests
for (int j=1;j<=mult-1;j++){
this.events.add(i+j, new Rest(e.duration));
}
if (leftover > MUSIC_EPSILON){
this.events.add(i+mult, new Rest(leftover));
}
return true;
}else{
//If the new event is longer, eat the rests after it until it fits
//Can only grow through rests and not other notes
float needed = e.duration - oldEvent.duration;
int j = i+1;
while (needed > MUSIC_EPSILON && j < this.events.size()){
MusicEvent next = this.events.get(j);
if (!(next instanceof Rest)){
return false;
}
needed -= next.duration;
j++;
}
if (needed > MUSIC_EPSILON){
return false;
}
this.events.set(i, e);
float extra = -needed;
for (int k=j-1;k>i;k--){
this.events.remove(k);
}
if (extra > MUSIC_EPSILON){
this.events.add(i+1, new Rest(extra));
}
return true;
}
}
boolean isFull(){
return abs(beatsRemaining()) < MUSIC_EPSILON; //Floating point math gets tiny rounding errors
}
boolean canAdd(MusicEvent e){
return restDuration() >= e.duration - MUSIC_EPSILON;
}
//Call this manually when a user places an accidental on a note in this measure
//Rule that accidentals apply all in a measure
void applyAccidental(int pitchClass, int modifier){
withinMeasureAccidentals.put(pitchClass, modifier); //Future notes have same accidental
}
void clearAccidentals(){
withinMeasureAccidentals.clear();
}
//Resolve when midi pitch using key sig + any within-measure accidentals
//Within-measure accidentals take prio over key signature, this is normal music
int resolvePitch(int midiNote, KeySignature keySig){
int pitchClass = midiNote%12;
if (withinMeasureAccidentals.containsKey(pitchClass)){
return midiNote + withinMeasureAccidentals.get(pitchClass);
}
return keySig.modifyPitch(midiNote);
}
int resolveEventPitch(Note note, KeySignature keySig){
//Note accidentals override key signature accidentals
if (note.hasAccidental){
return note.midiNote + note.accidentalModifier;
}
return resolvePitch(note.midiNote, keySig);
}
}
//Need to make drawing possible
class MusicalPiece{
String title;
ArrayList<Instrument> instruments;
ArrayList<ArrayList<Measure>> tracks; //tracks.get(i) = all measures for instrument i
KeySignature keySig;
TimeSignature timeSig;
int tempo; //BPM
volatile boolean playing;
MusicalPiece(String name, KeySignature k, TimeSignature t, int tempo){
this.title = name;
this.keySig = k;
this.timeSig = t;
this.tempo = tempo;
this.instruments = new ArrayList<Instrument>();
this.tracks = new ArrayList<ArrayList<Measure>>();
this.playing = false;
}
int measureCount(){
if (tracks.size()==0){
return 0;
}
return tracks.get(0).size();
}
Measure getMeasure(int trackID, int measureID){
return tracks.get(trackID).get(measureID);
}
//This is only called as a helper function
void addMeasure(int trackID, int i){ //i is the index within the track itself
//Adds a measure to trackID track
this.tracks.get(trackID).add(new Measure(trackID,i,this.timeSig));
}
//This is the one that should be user-facing
void addMeasure(){ //Add measures for every track
for (int t=0;t<tracks.size();t++){
addMeasure(t, tracks.get(t).size());
}
}
void addInstrument(Instrument instrument){
int trackID = tracks.size(); //New index
instruments.add(instrument);
tracks.add(new ArrayList<Measure>());
int count = max(1, measureCount());
for (int i=0;i<count;i++){
addMeasure(trackID, i);
}
saveHistoryState();
}
//trackID is the index of which track in the piece
//measureID is the index of the measure within a specific track
//eventID is the specific note within the measure that is being placed/edited
//Used for placing something at a beat position even if that beat is inside a rest
boolean placeEvent(int trackID, int measureID, int eventID, MusicEvent event){
Measure measure = getMeasure(trackID, measureID);
MusicEvent oldEvent = measure.events.get(eventID);
if (!(oldEvent instanceof Rest)){
return false;
}
boolean result = measure.changeEvent(event, eventID);
if (result){
saveHistoryState();
}
return result;
}
boolean placeEventAtBeat(int trackID, int measureID, float beat, MusicEvent event){
Measure measure = getMeasure(trackID, measureID);
if (beat < -MUSIC_EPSILON || beat + event.duration > timeSig.measureDuration() + MUSIC_EPSILON){
return false;
}
float currentBeat = 0;
for (int i=0;i<measure.events.size();i++){
MusicEvent oldEvent = measure.events.get(i);
float nextBeat = currentBeat + oldEvent.duration;
if (abs(beat-currentBeat) < MUSIC_EPSILON){
if (!(oldEvent instanceof Rest)){
return false;
}
return measure.changeEvent(event, i);
}
if (beat > currentBeat && beat < nextBeat - MUSIC_EPSILON){
if (!(oldEvent instanceof Rest)){
return false;
}
float before = beat - currentBeat;
float after = oldEvent.duration - before;
measure.events.set(i, new Rest(before));
measure.events.add(i+1, new Rest(after));
return measure.changeEvent(event, i+1);
}
currentBeat = nextBeat;
}
return false;
}
boolean editEvent(int trackID, int measureID, int eventID, MusicEvent event){
Measure measure = getMeasure(trackID, measureID);
return measure.changeEvent(event, eventID);
}
void startPlayback(){
play();
}
//Need to do threads for playing as to not interrupt the drawing and other issues
//Playback run in its own thread
void play(){
if (playing){
return;
}
playing = true;
Thread playbackThread = new Thread(new Runnable() {
public void run() {
//1 quarter note is 1000ms at 60bpm
float quarterMs = 60000.0 / tempo; //Converts to milliseconds
//Go through th piece one measure at a time
for (int m=0; m<measureCount() && playing; m++){ //Goes through each measure
float currentBeat = 0;
float measureDuration = timeSig.measureDuration();
while (currentBeat < measureDuration - MUSIC_EPSILON && playing){
float nextBeat = measureDuration;
//Check every track at this beat
for (int t=0;t<tracks.size();t++){ //Goesthrough each track
if (m >= tracks.get(t).size()){
continue;
}
Measure measure = getMeasure(t, m);
MusicEvent event = eventAtBeat(measure, currentBeat);
if (event != null){//Someting there
if (event instanceof Note){ //Is a note
Note n = (Note) event;
int resolved = measure.resolveEventPitch(n, keySig);
instruments.get(t).playNote(resolved, n.duration, quarterMs);
}else{
instruments.get(t).stopForRest(); //Stop playing for this specific track
}
}
float upcomingBeat = nextEventBeatAfter(measure, currentBeat);
if (upcomingBeat > currentBeat + MUSIC_EPSILON){
nextBeat = min(nextBeat, upcomingBeat);
}
}
if (nextBeat <= currentBeat + MUSIC_EPSILON){
break;
}
waitForBeats(nextBeat-currentBeat, quarterMs);
currentBeat = nextBeat;
}
}
stopAllInstruments();
playing = false;
}
});
playbackThread.start();
}
void stopPlayback(){
playing = false;
stopAllInstruments();
}
MusicEvent eventAtBeat(Measure measure, float beat){ //Finds the event at a specifc beat
float currentBeat = 0;
for (MusicEvent event: measure.events){
if (abs(currentBeat-beat) < MUSIC_EPSILON){
return event;
}
currentBeat += event.duration;
}
return null;
}
//Finds the next beat where someting starts so playback can jump there
float nextEventBeatAfter(Measure measure, float beat){
float currentBeat = 0;
for (MusicEvent event: measure.events){
if (currentBeat > beat + MUSIC_EPSILON){
return currentBeat;
}
currentBeat += event.duration;
}
return measure.timeSig.measureDuration();
}
void waitForBeats(float beats, float quarterMs){//Wait for these many beats
try{
Thread.sleep((long)(beats * quarterMs));
}
catch (Exception e){
}
}
void stopAllInstruments(){
for (Instrument instrument: instruments){
instrument.stopAll();
}
}
void addMeasure(int count){ //Add measures for every track
for (int i=0;i<count;i++){
for (int t=0;t<tracks.size();t++){
addMeasure(t, tracks.get(t).size());
}
}
saveHistoryState();
}
}