-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
1786 lines (1777 loc) · 88.6 KB
/
app.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
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 用这种方式(原始构造函数)的原因:解耦太难了,不解了。this全部指同一个
// 防止在html初始化之前getElement,所以封装成了构造函数,而不是直接写obj
function App() {
this.event = new EventTarget();
this.spectrum = document.getElementById('spectrum');
this.spectrum.ctx = this.spectrum.getContext('2d'); // 绘制相关参数的更改在this.resize中
this.keyboard = document.getElementById('piano');
this.keyboard.ctx = this.keyboard.getContext('2d', { alpha: false, desynchronized: true });
this.timeBar = document.getElementById('timeBar');
this.timeBar.ctx = this.timeBar.getContext('2d', { alpha: false, desynchronized: true });
this.midiMode = false;
this._width = 5; // 每格的宽度
Object.defineProperty(this, 'width', {
get: function () { return this._width; },
set: function (w) {
if (w <= 0) return;
this._width = w;
this.TimeBar.updateInterval();
this.HscrollBar.refreshSize(); // 刷新横向滑动条
this.TperP = this.dt / this._width; // 每个像素代表的时间
this.PperT = this._width / this.dt; // 每个时间代表的像素
}
});
this._height = 15; // 每格的高度
Object.defineProperty(this, 'height', {
get: function () { return this._height; },
set: function (h) {
if (h <= 0) return;
this._height = h;
this.Keyboard._ychange.set([
-1.5 * h, -2 * h, -1.5 * h, -1.5 * h, -2 * h, -2 * h, -1.5 * h,
-2 * h, -3 * h, -2 * h, -2 * h, -2 * h
]);
this.keyboard.ctx.font = `${h + 2}px Arial`;
this.spectrum.ctx.font = `${h}px Arial`;
}
});
this.ynum = 84; // 一共84个按键
this._xnum = 0; // 时间轴的最大长度
Object.defineProperty(this, 'xnum', { // midi模式下需要经常改变此值,故特设setter
get: function () { return this._xnum; },
set: function (n) {
if (n <= 0) return;
this._xnum = n;
this.HscrollBar.refreshSize(); // 刷新横向滑动条
this.idXend = Math.min(this._xnum, Math.ceil((this.scrollX + this.spectrum.width) / this._width));
}
});
this.scrollX = 0; // 视野左边和世界左边的距离
this.scrollY = 0; // 视野下边和世界下边的距离
this.idXstart = 0; // 开始的X序号
this.idYstart = 0; // 开始的Y序号
this.idXend = 0; // 在scroll2中更新
this.idYend = 0;
this.rectXstart = 0;// 目前只有Spectrogram.update在使用
this.rectYstart = 0;// 画布开始的具体y坐标(因为最下面一个不完整) 迭代应该减height 被画频谱、画键盘共享
this.loop = 0; // 接收requestAnimationFrame的返回
this.time = -1; // 当前时间 单位:毫秒 在this.AudioPlayer.update中更新
this.dt = 50; // 每次分析的时间间隔 单位毫秒 在this.Analyser.analyse中更新
this._mouseY = 0; // 鼠标当前y坐标
Object.defineProperty(this, 'mouseY', {
get: function () { return this._mouseY; },
set: function (y) {
this._mouseY = y;
this.Keyboard.highlight = Math.floor((this.scrollY + this.spectrum.height - y) / this._height) + 24;
}
});
this._mouseX = 0; // 鼠标当前x坐标
Object.defineProperty(this, 'mouseX', {
get: function () { return this._mouseX; },
set: function (x) {
this._mouseX = x;
this.MidiAction.frameXid = Math.floor((x + this.scrollX) / this._width);
}
});
this.audioContext = new AudioContext({ sampleRate: 44100 });
this.synthesizer = new TinySynth(this.audioContext);
this.Spectrogram = {
parent: this,
colorStep1: 100,
colorStep2: 240,
multiple: parseFloat(document.getElementById('multiControl').value),// 幅度的倍数
_spectrogram: null,
mask: '#25262daa',
getColor: (value) => { // 0-step1,是蓝色的亮度从0变为50%;step1-step2,是颜色由蓝色变为红色;step2-255,保持红色
value = value || 0;
let hue = 0, lightness = 50; // Red hue
if (value <= this.Spectrogram.colorStep1) {
hue = 240; // Blue hue
lightness = (value / this.Spectrogram.colorStep1) * 50; // Lightness from 0% to 50%
} else if (value <= this.Spectrogram.colorStep2) {
hue = 240 - ((value - this.Spectrogram.colorStep1) / (this.Spectrogram.colorStep2 - this.Spectrogram.colorStep1)) * 240;
} return `hsl(${hue}, 100%, ${lightness}%)`;
},
update: () => { // 不能用画图的坐标去限制,因为数据可能填不满画布 必须用id
const sp = this.Spectrogram;
const canvas = this.spectrum;
const ctx = this.spectrum.ctx;
let rectx = this.rectXstart;
for (let x = this.idXstart; x < this.idXend; x++) {
const s = sp._spectrogram[x];
let recty = this.rectYstart;
for (let y = this.idYstart; y < this.idYend; y++) {
ctx.fillStyle = sp.getColor(s[y] * sp.multiple);
ctx.fillRect(rectx, recty, this._width, -this._height);
recty -= this._height;
}
rectx += this._width;
}
let w = canvas.width - rectx;
// 画分界线
ctx.strokeStyle = "#FFFFFF";
ctx.beginPath();
for (let y = (((this.idYstart / 12) | 0) + 1) * 12,
rectY = canvas.height - this.height * y + this.scrollY,
dy = -12 * this.height;
y < this.idYend; y += 12, rectY += dy) {
ctx.moveTo(0, rectY);
ctx.lineTo(canvas.width, rectY);
} ctx.stroke();
// 填涂剩余部分
if (w > 0) {
ctx.fillStyle = '#25262d';
ctx.fillRect(rectx, 0, w, canvas.height);
}
// 铺底色以凸显midi音符
ctx.fillStyle = sp.mask;
ctx.fillRect(0, 0, rectx, canvas.height);
// 更新note
ctx.fillStyle = "#ffffff4f";
rectx = canvas.height - (this.Keyboard.highlight - 24) * this._height + this.scrollY;
ctx.fillRect(0, rectx, canvas.width, -this._height);
},
// 注意,getter 和 setter 的this指向为Spectrogram
get spectrogram() {
return this._spectrogram;
},
set spectrogram(s) {
if (!s) {
this._spectrogram = null;
this.parent.xnum = 0;
} else {
this._spectrogram = s;
this.parent.xnum = s.length; // 触发HscrollBar.refreshSize
this.parent.scroll2(); // 保持位置不变 本来是为了“一边分析一边绘制频谱”而设计的,虽然减少了等待但容易崩而且卡
}
},
get Alpha() {
return parseInt(this.mask.substring(7), 16);
},
set Alpha(a) {
a = Math.min(255, Math.max(a | 0, 0));
this.mask = '#25262d' + a.toString(16);
}
};
this.MidiAction = {
clickXid: 0,
clickYid: 0,
mode: 0, // 0: 笔模式 1: 选择模式
frameMode: 0, // 0: 框选 1: 列选 2: 行选
frameXid: -1, // 框选的终点的X序号(Y序号=this.Keyboard.highlight-24) 此变量便于绘制 如果是负数则不绘制
_tempdx: 0, // 鼠标移动记录上次
_tempdy: 0,
_anyAction: false, // 用于在选中多个后判断松开鼠标时应该如何处理选中
/* 一个音符 = {
y: 离散 和spectrum的y一致
x1: 离散 起点
x2: 离散 终点
ch: 音轨序号
selected: 是否选中
} */
selected: [], // 选中的音符 无序即可
midi: [], // 所有音符 需要维护有序性
// 多音轨
channelDiv: (() => {
const cd = new ChannelList(document.getElementById('funcSider'), this.synthesizer);
const saveOnReorder = () => this.snapshot.save();
const waitReorder = () => {
setTimeout(() => {
this.snapshot.save();
this.MidiAction.updateView();
cd.addEventListener('reorder', saveOnReorder);
}, 0); // 等待reorder的发生
}
cd.addEventListener('reorder', ({ detail }) => {
for (const nt of this.MidiAction.midi) {
nt.ch = detail[nt.ch];
} this.MidiAction.updateView();
});
cd.addEventListener('reorder', saveOnReorder);
cd.addEventListener('remove', ({ detail }) => {
cd.removeEventListener('reorder', saveOnReorder);
this.MidiAction.midi = this.MidiAction.midi.filter((nt) => nt.ch != detail.index);
this.MidiAction.selected = this.MidiAction.selected.filter((nt) => nt.ch != detail.index);
waitReorder();
});
cd.addEventListener('add', () => {
cd.removeEventListener('reorder', saveOnReorder);
waitReorder();
});
return cd;
})(),
insight: [], // 二维数组,每个元素为一个音轨视野内的音符 音符拾取依赖此数组
/**
* 更新this.MidiAction.insight
* 步骤繁琐,不必每次更新。触发时机:
* 1. channelDiv的reorder
* 2. midi的增删移动改变长度。由于都会调用且最后调用changeNoteY,所以只需要在changeNoteY中调用
* 3. scroll2
* 4. deleteNote
* 5. ctrlZ、ctrlY、ctrlV
*/
updateView: () => {
const m = this.MidiAction.midi;
const channel = Array.from(this.MidiAction.channelDiv.channel, () => []);
this.MidiAction.insight = channel;
// 原来用的二分有bug,所以干脆全部遍历
for (const nt of m) {
if (nt.x1 >= this.idXend) break;
if (nt.x2 < this.idXstart) continue;
if (nt.y < this.idYstart || nt.y >= this.idYend) continue;
channel[nt.ch].push(nt);
}
// midi模式下,视野要比音符宽一页,或超出视野半页
if(this.midiMode) {
const currentLen = this.Spectrogram.spectrogram.length;
let apage = this.spectrum.width / this._width;
let minLen = (m.length ? m[m.length - 1].x2 : 0) + apage * 1.5 | 0;
let viewLen = this.idXstart + apage | 0; // 如果视野在很外面,需要保持视野
if(viewLen > minLen) minLen = viewLen;
if(minLen != currentLen) this.Spectrogram.spectrogram.length = minLen; // length触发audio.duration和this.xnum
}
},
update: () => { // 按照insight绘制音符
const M = this.MidiAction;
const m = M.insight;
const s = this.spectrum.ctx;
const c = M.channelDiv.channel;
for (let ch = m.length - 1; ch >= 0; ch--) {
if (m[ch].length === 0 || (c[ch] && !c[ch].visible)) continue;
let ntcolor = c[ch].color;
for (const note of m[ch]) {
const params = [note.x1 * this._width - this.scrollX, this.spectrum.height - note.y * this._height + this.scrollY, (note.x2 - note.x1) * this._width, -this._height];
if (note.selected) {
s.fillStyle = '#ffffff';
s.fillRect(...params);
s.strokeStyle = ntcolor;
s.strokeRect(...params);
} else {
s.fillStyle = ntcolor;
s.fillRect(...params);
s.strokeStyle = '#ffffff';
s.strokeRect(...params);
}
}
} if (!M.mode || M.frameXid < 0) return;
// 绘制框选动作
s.fillStyle = '#f0f0f088';
let [xmin, xmax] = M.clickXid <= M.frameXid ? [M.clickXid, M.frameXid + 1] : [M.frameXid, M.clickXid + 1];
const Y = this.Keyboard.highlight - 24;
let [ymin, ymax] = Y <= M.clickYid ? [Y, M.clickYid + 1] : [M.clickYid, Y + 1];
let x1, x2, y1, y2;
if (M.frameMode == 1) { // 列选
x1 = xmin * this._width - this.scrollX;
x2 = (xmax - xmin) * this._width;
y1 = 0;
y2 = this.spectrum.height;
} else if (M.frameMode == 2) { // 行选
x1 = 0;
x2 = this.spectrum.width;
y1 = this.spectrum.height - ymax * this._height + this.scrollY;
y2 = (ymax - ymin) * this._height;
} else { // 框选
x1 = xmin * this._width - this.scrollX;
x2 = (xmax - xmin) * this._width;
y1 = this.spectrum.height - ymax * this._height + this.scrollY;
y2 = (ymax - ymin) * this._height;
} s.fillRect(x1, y1, x2, y2);
},
deleteNote: (save = true) => {
this.MidiAction.selected.forEach((v) => {
let i = this.MidiAction.midi.indexOf(v);
if (i != -1) this.MidiAction.midi.splice(i, 1);
});
this.MidiAction.selected.length = 0;
if (save) this.snapshot.save();
this.MidiAction.updateView();
},
clearSelected: () => { // 取消已选
this.MidiAction.selected.forEach(v => { v.selected = false; });
this.MidiAction.selected.length = 0;
},
/**
* 改变选中的音符的时长 依赖相对于点击位置的移动改变长度 所以需要提前准备好clickX
* 需要保证和changeNoteX同时只能使用一个
* @param {MouseEvent} e
*/
changeNoteDuration: (e) => {
this.MidiAction._anyAction = true;
// 兼容窗口滑动,以绝对坐标进行运算
let dx = (((e.offsetX + this.scrollX) / this._width) | 0) - this.MidiAction.clickXid;
this.MidiAction.selected.forEach((v) => {
if ((v.x2 += dx - this.MidiAction._tempdx) <= v.x1) v.x2 = v.x1 + 1;
});
this.MidiAction._tempdx = dx;
},
changeNoteY: () => { // 要求在trackMouse之后添加入spectrum的mousemoveEnent
this.MidiAction._anyAction = true;
let dy = this.Keyboard.highlight - 24 - this.MidiAction.clickYid;
this.MidiAction.selected.forEach((v) => {
v.y += dy - this.MidiAction._tempdy;
});
this.MidiAction._tempdy = dy;
this.MidiAction.updateView();
},
changeNoteX: (e) => {
this.MidiAction._anyAction = true;
let dx = (((e.offsetX + this.scrollX) / this._width) | 0) - this.MidiAction.clickXid;
this.MidiAction.selected.forEach((v) => {
let d = v.x2 - v.x1;
if ((v.x1 += dx - this.MidiAction._tempdx) < 0) v.x1 = 0; // 越界则设置为0
v.x2 = v.x1 + d;
});
this.MidiAction._tempdx = dx;
},
/**
* 框选音符的鼠标动作 由this.MidiAction.onclick_L调用
* 选中的标准:框住了音头
*/
selectAction: (mode = 0) => {
const m = this.MidiAction;
m.frameXid = m.clickXid; // 先置大于零,表示开始绘制
if (mode == 1) { // 列选
this.spectrum.addEventListener('mousemove', this.trackMouseX);
const up = () => {
this.spectrum.removeEventListener('mousemove', this.trackMouseX);
document.removeEventListener('mouseup', up);
let ch = m.channelDiv.selected;
if (ch) {
ch = ch.index;
let [xmin, xmax] = m.clickXid <= m.frameXid ? [m.clickXid, m.frameXid + 1] : [m.frameXid, m.clickXid + 1];
for (const nt of m.midi) nt.selected = (nt.x1 >= xmin && nt.x1 < xmax && nt.ch == ch);
m.selected = m.midi.filter(v => v.selected);
} m.frameXid = -1;
}; document.addEventListener('mouseup', up);
} else if (mode == 2) { // 行选
const up = () => {
document.removeEventListener('mouseup', up);
let ch = m.channelDiv.selected;
if (ch) {
ch = ch.index;
const Y = this.Keyboard.highlight - 24;
let [ymin, ymax] = Y <= m.clickYid ? [Y, m.clickYid + 1] : [m.clickYid, Y + 1];
for (const nt of m.midi) nt.selected = (nt.y >= ymin && nt.y < ymax && nt.ch == ch);
m.selected = m.midi.filter(v => v.selected);
} m.frameXid = -1;
}; document.addEventListener('mouseup', up);
} else { // 框选
this.spectrum.addEventListener('mousemove', this.trackMouseX);
const up = () => {
this.spectrum.removeEventListener('mousemove', this.trackMouseX);
document.removeEventListener('mouseup', up);
let ch = m.channelDiv.selected;
if (ch) {
ch = ch.index;
const Y = this.Keyboard.highlight - 24;
let [xmin, xmax] = m.clickXid <= m.frameXid ? [m.clickXid, m.frameXid + 1] : [m.frameXid, m.clickXid + 1];
let [ymin, ymax] = Y <= m.clickYid ? [Y, m.clickYid + 1] : [m.clickYid, Y + 1];
for (const nt of m.midi) nt.selected = (nt.x1 >= xmin && nt.x1 < xmax && nt.y >= ymin && nt.y < ymax && nt.ch == ch);
m.selected = m.midi.filter(v => v.selected);
} m.frameXid = -1; // 表示不在框选
}; document.addEventListener('mouseup', up);
}
},
/**
* 添加音符的鼠标动作 由this.MidiAction.onclick_L调用
*/
addNoteAction: () => {
const m = this.MidiAction;
if (!m.channelDiv.selected && !m.channelDiv.selectChannel(0)) return; // 如果没有选中则默认第一个
// 取消已选
m.clearSelected();
// 添加新音符,设置已选
const note = {
y: m.clickYid,
x1: m.clickXid,
x2: m.clickXid + 1,
ch: m.channelDiv.selected.index,
selected: true
}; m.selected.push(note);
{ // 二分插入
let l = 0, r = m.midi.length;
while (l < r) {
let mid = (l + r) >> 1;
if (m.midi[mid].x1 < note.x1) l = mid + 1;
else r = mid;
} m.midi.splice(l, 0, note);
}
m._anyAction = true;
m.updateView();
this.spectrum.addEventListener('mousemove', m.changeNoteDuration);
this.spectrum.addEventListener('mousemove', m.changeNoteY);
const removeEvent = () => {
this.spectrum.removeEventListener('mousemove', m.changeNoteDuration);
this.spectrum.removeEventListener('mousemove', m.changeNoteY);
document.removeEventListener('mouseup', removeEvent);
// 鼠标松开则存档
if (m._anyAction) this.snapshot.save();
}; document.addEventListener('mouseup', removeEvent);
},
onclick_L: (e) => {
//== step 1: 判断是否点在了音符上 ==//
const m = this.MidiAction;
const midi = m.midi;
m._anyAction = false;
// 为了支持在鼠标操作的时候能滑动,记录绝对位置
m._tempdx = m._tempdy = 0;
const x = m.clickXid = ((e.offsetX + this.scrollX) / this._width) | 0;
if (x >= this._xnum) { // 越界
m.clearSelected(); return;
}
const y = m.clickYid = this.Keyboard.highlight - 24;
// 找到点击的最近的音符 由于点击不经常,所以用遍历足矣 只需要遍历insight的音符
let n = null;
for (const ch of m.insight) {
// 每层挑选左侧最靠近的(如果有多个)
let distance = this._width * this._xnum;
for (const nt of ch) { // 由于来自midi,因此每个音轨内部是有序的
let dis = x - nt.x1;
if (dis < 0) break;
if (y == nt.y && x < nt.x2) {
if (dis < distance) {
distance = dis;
n = nt;
}
}
} if (n) break; // 只找最上层的
}
if (!n) { // 添加或框选音符
if (m.mode) m.selectAction(m.frameMode);
else m.addNoteAction();
return;
}
m.channelDiv.selectChannel(n.ch);
//== step 2: 如果点击到了音符,ctrl是否按下 ==/
if (e.ctrlKey) { // 有ctrl表示多选
if (n.selected) { // 已经选中了,取消选中
m.selected.splice(m.selected.indexOf(n), 1);
n.selected = false;
} else { // 没选中,添加选中
m.selected.push(n);
n.selected = true;
} return;
}
//== step 3: 单选时,是否选中了多个(事关什么时候取消选中) ==//
if (m.selected.length > 1 && n.selected) { // 如果选择了多个,在松开鼠标的时候处理选中
const up = () => {
if (!m._anyAction) { // 没有任何拖拽动作,说明为了单选
m.selected.forEach(v => { v.selected = false; });
m.selected.length = 0;
n.selected = true;
m.selected.push(n);
}
document.removeEventListener('mouseup', up);
}; document.addEventListener('mouseup', up);
} else { // 只选一个
if (n.selected) {
const up = () => {
if (!m._anyAction) { // 没有任何拖拽动作,说明为了取消选中
m.selected.forEach(v => { v.selected = false; });
m.selected.length = 0;
} document.removeEventListener('mouseup', up);
}; document.addEventListener('mouseup', up);
} else {
m.selected.forEach(v => { v.selected = false; });
m.selected.length = 0;
n.selected = true;
m.selected.push(n);
}
}
//== step 4: 如果点击到了音符,添加移动事件 ==//
if (((e.offsetX + this.scrollX) << 1) > (n.x2 + n.x1) * this._width) { // 靠近右侧,调整时长
this.spectrum.addEventListener('mousemove', m.changeNoteDuration);
this.spectrum.addEventListener('mousemove', m.changeNoteY);
const removeEvent = () => {
this.spectrum.removeEventListener('mousemove', m.changeNoteDuration);
this.spectrum.removeEventListener('mousemove', m.changeNoteY);
document.removeEventListener('mouseup', removeEvent);
// 鼠标松开则存档
if (m._anyAction) this.snapshot.save();
}; document.addEventListener('mouseup', removeEvent);
} else { // 靠近左侧,调整位置
this.spectrum.addEventListener('mousemove', m.changeNoteX);
this.spectrum.addEventListener('mousemove', m.changeNoteY);
const removeEvent = () => {
this.spectrum.removeEventListener('mousemove', m.changeNoteX);
this.spectrum.removeEventListener('mousemove', m.changeNoteY);
document.removeEventListener('mouseup', removeEvent);
this.MidiAction.midi.sort((a, b) => a.x1 - b.x1); // 排序非常重要 因为查找被点击的音符依赖顺序
// 鼠标松开则存档
if (m._anyAction) this.snapshot.save();
}; document.addEventListener('mouseup', removeEvent);
}
},
};
this.MidiPlayer = {
priorT: 1000 / 59, // 实际稳定在60帧,波动极小
realT: 1000 / 59,
_last: performance.now(),
lastID: -1,
restart: () => {
// 需要-1,防止当前时刻开始的音符不被播放
this.MidiPlayer.lastID = ((this.AudioPlayer.audio.currentTime * 1000 / this.dt) | 0) - 1;
},
update: () => {
const mp = this.MidiPlayer;
// 一阶预测
let tnow = performance.now();
// 由于requestAnimationFrame在离开界面的时候会停止,所以要设置必要的限定
if (tnow - mp._last < (mp.priorT << 1)) mp.realT = 0.2 * (tnow - mp._last) + 0.8 * mp.realT; // IIR低通滤波
mp._last = tnow;
if (this.AudioPlayer.audio.paused) return;
let predictT = this.time + 0.5 * (mp.realT + mp.priorT); // 先验和实测的加权和
let predictID = (predictT / this.dt) | 0;
// 寻找(mp.lastID, predictID]之间的音符
const m = this.MidiAction.midi;
if (m.length > 0) { // 二分查找要求长度大于0
let lastAt = m.length;
{ // 二分查找到第一个x1>mp.lastID的音符
let l = 0, r = lastAt - 1;
while (l <= r) {
let mid = (l + r) >> 1;
if (m[mid].x1 > mp.lastID) {
r = mid - 1;
lastAt = mid;
} else l = mid + 1;
}
}
for (; lastAt < m.length; lastAt++) {
const nt = m[lastAt];
if (nt.x1 > predictID) break;
if (this.MidiAction.channelDiv.channel[nt.ch].mute) continue;
this.synthesizer.play({
id: nt.ch,
f: this.Keyboard.freqTable[nt.y],
t: this.AudioPlayer.audio.currentTime - (nt.x1 * this.dt) / 1000,
last: (nt.x2 - nt.x1) * this.dt / 1000
});
}
}
mp.lastID = predictID;
}
};
this.AudioPlayer = {
name: "请上传文件", // 在this.Analyser.onfile中赋值
audio: new Audio(), // 在this.Analyser.onfile中重新赋值 此处需要一个占位
play_btn: document.getElementById('play-btn'),
durationString: '', // 在this.Analyser.audio.ondurationchange中更新
autoPage: false, // 自动翻页
repeat: true, // 是否区间循环
_crossFlag: false, // 上一时刻是否在重复区间终点左侧
EQfreq: [31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000],
// midiMode下url为duration
createAudio: (url) => {
return new Promise((resolve, reject) => {
const a = this.midiMode ? new FakeAudio(url) : new Audio(url);
a.loop = false;
a.volume = parseFloat(document.getElementById('audiovolumeControl').value);
a.ondurationchange = () => {
let ms = a.duration * 1000;
this.AudioPlayer.durationString = this.TimeBar.msToClockString(ms);
this.BeatBar.beats.maxTime = ms;
};
a.onended = () => {
this.time = 0;
this.AudioPlayer.stop();
};
a.onloadeddata = () => {
const ap = this.AudioPlayer;
if (!this.midiMode) {
ap.setEQ();
if (this.audioContext.state == 'suspended') this.audioContext.resume().then(() => a.pause());
document.title = ap.name + "~扒谱";
} else {
document.title = ap.name;
}
a.playbackRate = document.getElementById('speedControl').value; // load之后会重置速度
this.time = 0;
resolve(a);
a.onloadeddata = null; // 一次性 防止多次构造
ap.play_btn.firstChild.textContent = this.TimeBar.msToClockString(this.time);
ap.play_btn.lastChild.textContent = ap.durationString;
};
a.onerror = (e) => { // 如果正常分析,是用不到这个回调的,因为WebAudioAPI读取就会报错。但上传已有结果不会再分析
// 发现一些如mov格式的视频,不在video/的支持列表中,用.readAsDataURL转为base64后无法播放,会触发这个错误
// 改正方法是用URL.createObjectURL(file)生成一个blob地址而不是解析为base64
reject(e);
this.event.dispatchEvent(new Event('fileerror'));
};
this.AudioPlayer.setAudio(a);
});
},
update: () => {
const A = this.AudioPlayer;
const a = A.audio;
const btn = A.play_btn;
if (a.readyState != 4 || a.paused) return;
this.time = a.currentTime * 1000; // 【重要】更新时间
// 重复区间
let crossFlag = this.time < this.TimeBar.repeatEnd;
if (A.repeat && this.TimeBar.repeatEnd >= this.TimeBar.repeatStart) { // 重复且重复区间有效
let crossFlag = this.time < this.TimeBar.repeatEnd;
if (A._crossFlag && !crossFlag) { // 从重复区间终点左侧到右侧
this.time = this.TimeBar.repeatStart;
a.currentTime = this.time / 1000;
}
}
A._crossFlag = crossFlag;
btn.firstChild.textContent = this.TimeBar.msToClockString(this.time);
btn.lastChild.textContent = A.durationString;
// 自动翻页
if (A.autoPage && (this.time > this.idXend * this.dt || this.time < this.idXstart * this.dt)) {
this.scroll2(((this.time / this.dt - 1) | 0) * this._width, this.scrollY); // 留一点空位
}
},
/**
* 在指定的毫秒数开始播放
* @param {Number} at 开始的毫秒数 如果是负数,则从当下开始
*/
start: (at) => {
const a = this.AudioPlayer.audio;
if (a.readyState != 4) return;
if (at >= 0) a.currentTime = at / 1000;
this.AudioPlayer._crossFlag = false; // 置此为假可以暂时取消重复区间
this.MidiPlayer.restart();
if (a.readyState == 4) a.play();
else a.oncanplay = () => {
a.play();
a.oncanplay = null;
};
},
stop: () => {
this.AudioPlayer.audio.pause();
this.synthesizer.stopAll();
},
setEQ: (f = this.AudioPlayer.EQfreq) => {
const a = this.AudioPlayer.audio;
if (a.EQ) return;
// 由于createMediaElementSource对一个audio只能调用一次,所以audio的EQ属性只能设置一次
const source = this.audioContext.createMediaElementSource(a);
let last = source;
a.EQ = {
source: source,
filter: f.map((v) => {
const filter = this.audioContext.createBiquadFilter();
filter.type = "peaking";
filter.frequency.value = v;
filter.Q.value = 1;
filter.gain.value = 0;
last.connect(filter);
last = filter;
return filter;
})
};
last.connect(this.audioContext.destination);
},
setAudio: (newAudio) => {
const A = this.AudioPlayer.audio;
if (A) {
A.pause();
A.onerror = null; // 防止触发fileerror
A.src = '';
if (A.EQ) {
A.EQ.source.disconnect();
for (const filter of A.EQ.filter) filter.disconnect();
}
// 配合传参为URL.createObjectURL(file)使用,防止内存泄露
URL.revokeObjectURL(this.AudioPlayer.audio.src);
}
this.AudioPlayer.audio = newAudio;
}
};
this.Keyboard = {
highlight: -1, // 选中了哪个音 音的编号以midi协议为准 C1序号为24 根this.mouseY一起在onmousemove更新
freqTable: new FreqTable(440), // 在this.Analyser.analyse中赋值
// 以下为画键盘所需
_idchange: new Int8Array([2, 2, 1, 2, 2, 2, -10, 2, 3, 2, 2, 2]), // id变化
_ychange: new Float32Array(12), // 纵坐标变化,随this.height一起变化
update: () => {
const kbd = this.Keyboard;
const ctx = this.keyboard.ctx;
const w = this.keyboard.width;
const w2 = w * 0.618;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, w, this.keyboard.height);
let noteID = this.idYstart + 24; // 最下面对应的音的编号
let note = noteID % 12; // 一个八度中的第几个音
let baseY = this.rectYstart + note * this._height; // 这个八度左下角的y坐标
noteID -= note; // 这个八度C的编号
while (true) {
ctx.beginPath(); // 必须写循环内
ctx.fillStyle = 'orange';
for (let i = 0, rectY = baseY, id = noteID; i < 7 & rectY > 0; i++) { // 画白键
let dy = kbd._ychange[i];
if (this.Keyboard.highlight == id) ctx.fillRect(0, rectY, w, dy); // 被选中的
ctx.moveTo(0, rectY); // 画线即可 下划线
ctx.lineTo(w, rectY);
rectY += dy;
id += kbd._idchange[i];
} ctx.stroke();
// 写音阶名
ctx.fillStyle = "black"; ctx.fillText(Math.floor(noteID / 12) - 1, w - this._height * 0.75, baseY - this._height * 0.3);
baseY -= this._height; noteID++;
for (let i = 7; i < 12; i++) {
if (this.Keyboard.highlight == noteID) { // 考虑到只要画一次高亮,不必每次都改fillStyle
ctx.fillStyle = '#Ffa500ff';
ctx.fillRect(0, baseY, w2, -this._height);
ctx.fillStyle = 'black';
} else ctx.fillRect(0, baseY, w2, -this._height);
baseY += kbd._ychange[i];
noteID += kbd._idchange[i];
if (baseY < 0) return;
}
}
},
mousedown: () => { // 鼠标点击后发声
let ch = this.MidiAction.channelDiv.selected;
if (!ch || ch.mute) return;
ch = ch ? ch.ch : this.synthesizer;
let nt = ch.play({ f: this.Keyboard.freqTable[this.Keyboard.highlight - 24] });
let last = this.Keyboard.highlight; // 除颤
const tplay = this.audioContext.currentTime;
const move = () => {
if (last === this.Keyboard.highlight) return;
last = this.Keyboard.highlight;
let dt = this.audioContext.currentTime - tplay;
this.synthesizer.stop(nt, dt > 0.3 ? 0 : dt - 0.3);
nt = ch.play({ f: this.Keyboard.freqTable[this.Keyboard.highlight - 24] });
}; document.addEventListener('mousemove', move);
const up = () => {
let dt = this.audioContext.currentTime - tplay;
this.synthesizer.stop(nt, dt > 0.5 ? 0 : dt - 0.5);
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', up);
}; document.addEventListener('mouseup', up);
}
}; this.height = this._height; // 更新this.Keyboard._ychange
this.TimeBar = {
interval: 10, // 每个标注的间隔块数 在updateInterval中更新
// 重复区间参数 单位:毫秒 如果start>end则区间不起作用
repeatStart: -1,
repeatEnd: -1,
/**
* 毫秒转 分:秒:毫秒
* @param {Number} ms 毫秒数
* @returns [分,秒,毫秒]
*/
msToClock: (ms) => {
return [
Math.floor(ms / 60000),
Math.floor((ms % 60000) / 1000),
ms % 1000 | 0
];
},
msToClockString: (ms) => {
const t = this.TimeBar.msToClock(ms);
return `${t[0].toString().padStart(2, "0")}:${t[1].toString().padStart(2, "0")}:${t[2].toString().padStart(3, "0")}`;
},
// timeBar的上半部分画时间轴
update: () => {
const canvas = this.timeBar;
const ctx = this.timeBar.ctx;
const tb = this.TimeBar;
let idstart = Math.ceil(this.idXstart / tb.interval - 0.1); // 画面中第一个时间点的序号
let dt = tb.interval * this.dt; // 时间的步长
let dp = this.width * tb.interval; // 像素的步长
let timeAt = dt * idstart; // 对应的毫秒
let p = idstart * dp - this.scrollX; // 对应的像素
let h = canvas.height >> 1; // 上半部分
ctx.fillStyle = '#25262d';
ctx.fillRect(0, 0, canvas.width, h);
ctx.fillStyle = '#8e95a6';
//== 画刻度 标时间 ==//
ctx.strokeStyle = '#ff0000';
ctx.beginPath();
for (let endPix = canvas.width + (dp >> 1); p < endPix; p += dp, timeAt += dt) {
ctx.moveTo(p, 0);
ctx.lineTo(p, h);
ctx.fillText(tb.msToClockString(timeAt), p - 28, 16);
} ctx.stroke();
//== 画重复区间 ==//
let begin = this._width * tb.repeatStart / this.dt - this.scrollX; // 单位:像素
let end = this._width * tb.repeatEnd / this.dt - this.scrollX;
const spectrum = this.spectrum.ctx;
const spectrumHeight = this.spectrum.height;
// 画线
if (begin >= 0 && begin < canvas.width) { // 画左边
ctx.beginPath(); spectrum.beginPath();
ctx.strokeStyle = spectrum.strokeStyle = '#20ff20';
ctx.moveTo(begin, 0); ctx.lineTo(begin, canvas.height);
spectrum.moveTo(begin, 0); spectrum.lineTo(begin, spectrumHeight);
ctx.stroke(); spectrum.stroke();
}
if (end >= 0 && end < canvas.width) { // 画右边
ctx.beginPath(); spectrum.beginPath();
ctx.strokeStyle = spectrum.strokeStyle = '#ff2020';
ctx.moveTo(end, 0); ctx.lineTo(end, canvas.height);
spectrum.moveTo(end, 0); spectrum.lineTo(end, spectrumHeight);
ctx.stroke(); spectrum.stroke();
}
// 画区间 如果begin>end则区间不起作用,不绘制
if (begin < end) {
begin = Math.max(begin + 1, 0); end = Math.min(end - 1, canvas.width);
ctx.fillStyle = spectrum.fillStyle = '#80808044';
ctx.fillRect(begin, 0, end - begin, canvas.height);
spectrum.fillRect(begin, 0, end - begin, spectrumHeight);
}
//== 画当前时间指针 ==//
spectrum.strokeStyle = 'white';
begin = this.time / this.dt * this._width - this.scrollX;
if (begin >= 0 && begin < canvas.width) {
spectrum.beginPath();
spectrum.moveTo(begin, 0);
spectrum.lineTo(begin, spectrumHeight);
spectrum.stroke();
}
},
updateInterval: () => { // 根据this.width改变 在width的setter中调用
const fontWidth = this.timeBar.ctx.measureText('00:00:000').width * 1.2;
// 如果间距小于fontWidth则细分
this.TimeBar.interval = Math.max(1, Math.ceil(fontWidth / this._width));
},
contextMenu: new ContextMenu([
{
name: "设置重复区间开始位置",
callback: (e_father, e_self) => {
this.TimeBar.repeatStart = (e_father.offsetX + this.scrollX) * this.TperP;
}
}, {
name: "设置重复区间结束位置",
callback: (e_father, e_self) => {
this.TimeBar.repeatEnd = (e_father.offsetX + this.scrollX) * this.TperP;
}
}, {
name: "取消重复区间",
onshow: () => this.TimeBar.repeatStart >= 0 || this.TimeBar.repeatEnd >= 0,
callback: () => {
this.TimeBar.repeatStart = -1;
this.TimeBar.repeatEnd = -1;
}
}, {
name: "从此处播放",
callback: (e_father, e_self) => {
this.AudioPlayer.stop();
this.AudioPlayer.start((e_father.offsetX + this.scrollX) * this.TperP);
}
}
])
};
this.BeatBar = {
beats: new Beats(),
update: () => {
const canvas = this.timeBar;
const ctx = this.timeBar.ctx;
ctx.fillStyle = '#2e3039';
const h = canvas.height >> 1;
ctx.fillRect(0, h, canvas.width, canvas.width);
ctx.fillStyle = '#8e95a6';
const spectrum = this.spectrum.ctx;
const spectrumHeight = this.spectrum.height;
ctx.strokeStyle = '#f0f0f0f0';
const iterator = this.BeatBar.beats.iterator(this.scrollX * this.TperP, true);
ctx.beginPath(); spectrum.beginPath();
while (1) {
let measure = iterator.next();
if (measure.done) break;
measure = measure.value;
let x = measure.start * this.PperT - this.scrollX;
if (x > canvas.width) break;
ctx.moveTo(x, h);
ctx.lineTo(x, canvas.height);
spectrum.strokeStyle = '#a0a0a0';
spectrum.moveTo(x, 0);
spectrum.lineTo(x, spectrumHeight);
// 写字
let Interval = measure.interval * this.PperT;
ctx.fillText(Interval < 38 ? measure.id : `${measure.id}. ${measure.beatNum}/${measure.beatUnit}`, x + 2, h + 14);
// 画更细的节拍线
let dp = Interval / measure.beatNum;
if (dp < 20) continue;
spectrum.strokeStyle = '#909090';
for (let i = measure.beatNum; i > 0; i--, x += dp) {
spectrum.moveTo(x, 0);
spectrum.lineTo(x, spectrumHeight);
}
} ctx.stroke(); spectrum.stroke();
},
contextMenu: new ContextMenu([
{
name: "设置小节",
callback: (e_father, e_self) => {
const bs = this.BeatBar.beats;
const m = bs.setMeasure((e_father.offsetX + this.scrollX) * this.TperP, undefined, true);
let tempDiv = document.createElement('div');
tempDiv.innerHTML = `
<div class="request-cover">
<div class="card hvCenter"><label class="title">小节${m.id}设置</label>
<div class="layout"><span>拍数</span><input type="text" name="ui-ask" step="1" max="16" min="1"></div>
<div class="layout"><span>音符</span><select name="ui-ask">
<option value="2">2分</option>
<option value="4">4分</option>
<option value="8">8分</option>
<option value="16">16分</option>
</select></div>
<div class="layout"><span>BPM:</span><input type="number" name="ui-ask" min="1"></div>
<div class="layout"><span>(忽略以上)和上一小节一样</span><input type="checkbox" name="ui-ask"></div>
<div class="layout"><span>应用到后面相邻同类型小节</span><input type="checkbox" name="ui-ask" checked></div>
<div class="layout"><button class="ui-cancel">取消</button><button class="ui-confirm">确定</button></div>
</div>
</div>`;
const Pannel = tempDiv.firstElementChild;
document.body.insertBefore(Pannel, document.body.firstChild);
Pannel.tabIndex = 0;
Pannel.focus();
function close() { Pannel.remove(); }
const inputs = Pannel.querySelectorAll('[name="ui-ask"]');
const btns = Pannel.getElementsByTagName('button');
inputs[0].value = m.beatNum; // 拍数
inputs[1].value = m.beatUnit; // 音符类型
inputs[2].value = m.bpm; // bpm
btns[0].onclick = close;
btns[1].onclick = () => {
if (!inputs[4].checked) { // 后面不变
bs.setMeasure(m.id + 1, false); // 让下一个生成实体
}
if (inputs[3].checked) { // 和上一小节一样
let last = bs.getMeasure(m.id - 1, false);
m.copy(last);
} else {
m.beatNum = parseInt(inputs[0].value);
m.beatUnit = parseInt(inputs[1].value);
m.bpm = parseInt(inputs[2].value);
} bs.check(); close();
};
}
}, {
name: "后方插入一小节",
callback: (e_father) => {
this.BeatBar.beats.add((e_father.offsetX + this.scrollX) * this.TperP, true);
}
}, {
name: "重置后面所有小节",
callback: (e_father) => {
let base = this.BeatBar.beats.getBaseIndex((e_father.offsetX + this.scrollX) * this.TperP, true);
this.BeatBar.beats.splice(base + 1);
}
}, {
name: '<span style="color: red;">删除该小节</span>',
callback: (e_father, e_self) => {
this.BeatBar.beats.delete((e_father.offsetX + this.scrollX) * this.TperP, true);
}
}
]),
belongID: -1, // 小节线前一个小节的id
moveCatch: (e) => { // 画布上光标移动到小节线上可以进入调整模式
if (e.offsetY < this.timeBar.height >> 1) {
this.timeBar.classList.remove('selecting');
this.BeatBar.belongID = -1;
return;
}
let timeNow = (e.offsetX + this.scrollX) * this.TperP;
let m = this.BeatBar.beats.getMeasure(timeNow, true);
if (m == null) {
this.BeatBar.belongID = -1;
this.timeBar.classList.remove('selecting');
return;
}
let threshold = 6 * this.TperP;
if (timeNow - m.start < threshold) {
this.BeatBar.belongID = m.id - 1;
this.timeBar.classList.add('selecting');
} else if (m.start + m.interval - timeNow < threshold) {
this.BeatBar.belongID = m.id;
this.timeBar.classList.add('selecting');
} else {
this.BeatBar.belongID = -1;
this.timeBar.classList.remove('selecting');
}
}
};
// 小插件对象
this.pitchNameDisplay = { // 音名显示 配合设置中的checkbox使用
_showPitchName: null,
showPitchName: (ifshow) => {