-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2614 lines (2263 loc) · 73.4 KB
/
index.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
// Click 'Effect' or 'BGM' button will cause GLOBAL var changed
let Effect = 0
let BGM = 0
let IS_RECORDING = 0
let start_recorded = null
let thesound = null
// End of GLOBAL var
init_record();
window.addEventListener('load', () => {
let C = [], M = [], Play = null, Record = null
for(let i=0;i<6;i++) {
C.push(document.querySelector('#C'+(i+1)))
C[i].addEventListener('click', () => {
if(Effect!=0) {
let pre = document.querySelector('#C'+Effect)
pre.firstElementChild.classList.remove('card-img-checked')
pre.firstElementChild.classList.add('card-img')
}
Effect = i+1
let after = document.querySelector('#C'+Effect)
after.firstElementChild.classList.add('card-img-checked')
after.firstElementChild.classList.remove('card-img')
console.log(Effect)
})
M.push(document.querySelector('#M'+(i+1)))
M[i].addEventListener('click', () => {
if(BGM!=0) {
let pre = document.querySelector('#M'+BGM)
pre.firstElementChild.classList.remove('card-img-checked')
pre.firstElementChild.classList.add('card-img')
}
BGM = i+1
let after = document.querySelector('#M'+BGM)
after.firstElementChild.classList.add('card-img-checked')
after.firstElementChild.classList.remove('card-img')
console.log(BGM)
})
}
Record = document.querySelector('#Record')
Play = document.querySelector('#Play')
Record.addEventListener('click', () => {
if(IS_RECORDING === 0){
start_recorded = record(0.5);
IS_RECORDING = 1;
}
else{
IS_RECORDING = 0;
thesound = start_recorded();
}
})
Play.addEventListener('click', () => {
play_it(thesound(), changes[Effect], bgms[BGM]);
})
})
/*****************************************************************************/
function change_fft(sound){
var data = discretize(get_wave(sound), get_duration(sound));
const datal = data.length;
const size = Math.pow(2, Math.ceil(Math.log(datal) / Math.LN2));
const f = new FFT(size);
const out=f.createComplexArray();
for(i = datal; i < size; i++){
data[i] = 0;
}
const data2 = f.toComplexArray(data);
f.transform(out,data2);
for(i = size;i < 2 * size; i++){
out[i] = 0;
}
for(i = Math.floor(2000 * (size / FS)); i > 700 * (size / FS); i--){
out[2 * i] = out[2 * i - Math.floor(400 * (2 * size / FS))];
out[2 * i + 1] = out[2 * i + 1 - Math.floor(400 * (2 * size / FS))];
}
for(i = Math.floor(300 * (size / FS)); i < 700 * (size / FS); i++){
out[2 * i] = 0;
out[2 * i + 1] = 0;
}
var _data=new Array(size);
f.inverseTransform(_data,out);
const _data2 = f.fromComplexArray(_data);
_data2.length = data.length;
return array_to_sound(_data2);
}
function array_to_sound(sound_array){
return make_sound(t => sound_array[Math.floor(t*FS)], Math.floor(sound_array.length/FS));
}
function change_volume(sound, k) {
return make_sound(t => k * head(sound)(t), tail(sound));
}
// play changed sound with background music
function play_it(sound, change, bgm) {
play(play_with_bgm(change_volume(bgm, 0.3), change(sound)));
}
function play_with_bgm(bgm, ss2) {
var dur1 = tail(bgm);
var dur2 = tail(ss2);
while(dur1<dur2){
bgm = consecutively(list(bgm,bgm));
dur1 = tail(bgm);
}
var wave1 = head(bgm);
var wave2 = head(ss2);
// new_wave assumes sound discipline (ie, wave(t) = 0 after t > dur)
var new_wave = t => wave1(t) + wave2(t);
// new_dur is higher of the two dur
var new_dur = dur1 < dur2 ? dur1 : dur2;
return pair(new_wave, new_dur);
}
// To record sound,run
// const stop = record_start();
// and seconds later run
// record_stop(stop)
function record_start() {
return record(0.5);
}
function record_stop(stop){
return stop();
}
/* some bgm */
function bgm_silence(){
return silence_sound(1);
}
function bgm_Children_Song(){
return consecutively(list(
piano(72,0.3),piano(72,0.3),piano(79,0.3),piano(79,0.3),piano(81,0.3),piano(81,0.3),piano(79,0.5),
piano(77,0.3),piano(77,0.3),piano(76,0.3),piano(76,0.3),piano(74,0.3),piano(74,0.3),piano(72,0.5),
piano(79,0.3),piano(79,0.3),piano(77,0.3),piano(77,0.3),piano(76,0.3),piano(76,0.3),piano(74,0.5),
piano(79,0.3),piano(79,0.3),piano(77,0.3),piano(77,0.3),piano(76,0.3),piano(76,0.3),piano(74,0.5),
piano(72,0.3),piano(72,0.4),piano(79,0.4),piano(79,0.4),piano(81,0.4),piano(81,0.4),piano(79,0.5),
piano(77,0.3),piano(77,0.4),piano(76,0.5),piano(76,0.5),piano(74,0.5),piano(74,0.5),piano(72,0.7)
));
}
function bgm_celebrate(){
return consecutively(list(
piano(79,0.3),piano(79,0.3),piano(81,0.5),piano(79,0.5),piano(84,0.5),piano(83,0.7),
piano(79,0.3),piano(79,0.3),piano(81,0.5),piano(79,0.5),piano(86,0.5),piano(84,0.7),
piano(79,0.3),piano(79,0.3),piano(91,0.5),piano(88,0.5),piano(84,0.5),piano(83,0.5),piano(81,0.7),
piano(89,0.3),piano(89,0.3),piano(88,0.5),piano(84,0.5),piano(86,0.5),piano(84,0.7)
));
}
function bgm_lyric(){
return consecutively(list(
violin(72,0.3),violin(72,0.3),violin(74,0.3),violin(76,0.3),violin(76,0.3),violin(77,0.3),violin(79,0.3),
violin(81,0.3),violin(79,0.3),violin(76,0.7),violin(79,0.3),violin(77,0.3),violin(76,0.3),violin(74,0.6),
violin(77,0.3),violin(76,0.3),violin(74,0.3),violin(72,0.6),violin(72,0.3),violin(72,0.3),violin(74,0.3),
violin(76,0.3),violin(76,0.3),violin(77,0.3),violin(79,0.3),violin(81,0.3),violin(79,0.3),violin(76,0.7),
violin(79,0.3),violin(77,0.3),violin(76,0.3),violin(74,0.3),violin(76,0.3),violin(74,0.3),violin(72,0.6)
));
}
function bgm_classical(){
return consecutively(list(
violin(88,0.3),violin(86,0.3),violin(88,0.3),violin(86,0.3),violin(88,0.3),violin(83,0.3),violin(86,0.3),
violin(84,0.3),violin(81,0.7),violin(72,0.3),violin(76,0.3),violin(81,0.3),violin(83,0.7),violin(76,0.3),
violin(79,0.3),violin(83,0.3),violin(84,1),violin(88,0.3),violin(86,0.3),violin(88,0.3),violin(86,0.3),
violin(88,0.3),violin(83,0.3),violin(86,0.3),violin(84,0.3),violin(81,0.7),violin(72,0.3),violin(76,0.3),
violin(81,0.3),violin(83,0.7),violin(76,0.3),violin(79,0.3),violin(83,0.3),violin(81,1)
));
}
function bgm_folk(){
return consecutively(list(
piano(74,0.5),piano(79,0.5),piano(76,0.3),piano(74,0.3),piano(76,0.3),piano(76,0.3),
piano(79,0.3),piano(76,0.3),piano(74,0.3),piano(72,0.3),piano(74,0.6),piano(74,0.6),
piano(74,0.6),piano(79,0.6),piano(74,0.3),piano(74,0.3),piano(76,0.3),piano(79,0.3),
piano(76,0.3),piano(74,0.3),piano(72,0.3),piano(69,0.3),piano(72,0.5),piano(72,0.5),
piano(72,0.5),piano(76,0.5),piano(74,0.3),piano(76,0.3),piano(65,0.3),piano(65,0.3),
piano(72,0.3),piano(74,0.3),piano(69,0.3),piano(67,0.3),piano(69,0.6),piano(69,0.6),
piano(72,0.3),piano(72,0.3),piano(72,0.3),piano(74,0.3),piano(69,0.3),piano(67,0.3),
piano(67,0.3),piano(64,0.3),piano(67,1)
));
}
function bgm_Country_Side(){
return c_major_scale_sound;
}
/* some function to change sound */
function change_nochange(sound) {
return sound;
}
function change_fatBoy(sound){
const new_wave = t=> get_wave(sound)(t*0.8);
return make_sound(new_wave,get_duration(sound)*(5/4));
}
function change_valleyEcho(sound){
return simultaneously(list(pair(t => 1.5 * (head(sound)(t)), tail(sound)),
pair(t => t < 0.3 ?0 :0.5*(head(sound)((t-0.3))), tail(sound) + 0.3),
pair(t => t < 0.5 ?0 :0.4*(head(sound)((t-0.5))), tail(sound) + 0.5),
pair(t => t < 0.7 ?0 :0.3*(head(sound)((t-0.7))), tail(sound) + 0.7),
pair(t => t < 0.8 ?0 :0.2*(head(sound)((t-0.8))), tail(sound) + 0.8),
pair(t => t < 0.9 ?0 :0.1*(head(sound)((t-0.9))), tail(sound) + 0.9)));
}
function change_cuteMonster(sound){
return pair(t => head(sound)(1.4 * t), tail(sound));
}
function change_backInTime(sound){
const w = get_wave(sound);
const d = get_duration(sound);
return make_sound(t => w(d - t), d);
}
let bgms = [bgm_silence(), bgm_silence(), bgm_celebrate(), bgm_folk(), bgm_Children_Song(), bgm_lyric(), bgm_classical()];
let changes = [change_nochange, change_nochange, change_fatBoy, change_backInTime, change_valleyEcho, change_cuteMonster, change_fft];
/*****************************************************************************/
// list.js: Supporting lists in the Scheme style, using pairs made
// up of two-element JavaScript array (vector)
// Author: Martin Henz
// array test works differently for Rhino and
// the Firefox environment (especially Web Console)
function array_test(x) {
if (Array.isArray === undefined) {
return x instanceof Array
} else {
return Array.isArray(x)
}
}
// pair constructs a pair using a two-element array
// LOW-LEVEL FUNCTION, NOT SOURCE
function pair(x, xs) {
return [x, xs]
}
// is_pair returns true iff arg is a two-element array
// LOW-LEVEL FUNCTION, NOT SOURCE
function is_pair(x) {
return array_test(x) && x.length === 2
}
// head returns the first component of the given pair,
// throws an exception if the argument is not a pair
// LOW-LEVEL FUNCTION, NOT SOURCE
function head(xs) {
if (is_pair(xs)) {
return xs[0]
} else {
throw new Error('head(xs) expects a pair as argument xs, but encountered ' + xs)
}
}
// tail returns the second component of the given pair
// throws an exception if the argument is not a pair
// LOW-LEVEL FUNCTION, NOT SOURCE
function tail(xs) {
if (is_pair(xs)) {
return xs[1]
} else {
throw new Error('tail(xs) expects a pair as argument xs, but encountered ' + xs)
}
}
// is_null returns true if arg is exactly null
// LOW-LEVEL FUNCTION, NOT SOURCE
function is_null(xs) {
return xs === null
}
// is_list recurses down the list and checks that it ends with the empty list []
// does not throw Value exceptions
// LOW-LEVEL FUNCTION, NOT SOURCE
function is_list(xs) {
for (; ; xs = tail(xs)) {
if (is_null(xs)) {
return true
} else if (!is_pair(xs)) {
return false
}
}
}
// list makes a list out of its arguments
// LOW-LEVEL FUNCTION, NOT SOURCE
function list() {
let the_list = null
for (let i = arguments.length - 1; i >= 0; i--) {
the_list = pair(arguments[i], the_list)
}
return the_list
}
// list_to_vector returns vector that contains the elements of the argument list
// in the given order.
// list_to_vector throws an exception if the argument is not a list
// LOW-LEVEL FUNCTION, NOT SOURCE
function list_to_vector(lst) {
const vector = []
while (!is_null(lst)) {
vector.push(head(lst))
lst = tail(lst)
}
return vector
}
// vector_to_list returns a list that contains the elements of the argument vector
// in the given order.
// vector_to_list throws an exception if the argument is not a vector
// LOW-LEVEL FUNCTION, NOT SOURCE
function vector_to_list(vector) {
let result = null
for (let i = vector.length - 1; i >= 0; i = i - 1) {
result = pair(vector[i], result)
}
return result
}
// returns the length of a given argument list
// throws an exception if the argument is not a list
function length(xs) {
let i = 0
while (!is_null(xs)) {
i += 1
xs = tail(xs)
}
return i
}
// map applies first arg f to the elements of the second argument,
// assumed to be a list.
// f is applied element-by-element:
// map(f,[1,[2,[]]]) results in [f(1),[f(2),[]]]
// map throws an exception if the second argument is not a list,
// and if the second argument is a non-empty list and the first
// argument is not a function.
// tslint:disable-next-line:ban-types
function map(f, xs) {
return is_null(xs) ? null : pair(f(head(xs)), map(f, tail(xs)))
}
// build_list takes a non-negative integer n as first argument,
// and a function fun as second argument.
// build_list returns a list of n elements, that results from
// applying fun to the numbers from 0 to n-1.
// tslint:disable-next-line:ban-types
function build_list(n, fun) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
'build_list(n, fun) expects a positive integer as ' + 'argument n, but encountered ' + n
)
}
// tslint:disable-next-line:ban-types
function build(i, alreadyBuilt) {
if (i < 0) {
return alreadyBuilt
} else {
return build(i - 1, pair(fun(i), alreadyBuilt))
}
}
return build(n - 1, null)
}
// for_each applies first arg fun to the elements of the list passed as
// second argument. fun is applied element-by-element:
// for_each(fun,[1,[2,[]]]) results in the calls fun(1) and fun(2).
// for_each returns true.
// for_each throws an exception if the second argument is not a list,
// and if the second argument is a non-empty list and the
// first argument is not a function.
// tslint:disable-next-line:ban-types
function for_each(fun, xs) {
if (!is_list(xs)) {
throw new Error('for_each expects a list as argument xs, but encountered ' + xs)
}
for (; !is_null(xs); xs = tail(xs)) {
fun(head(xs))
}
return true
}
// reverse reverses the argument list
// reverse throws an exception if the argument is not a list.
function reverse(xs) {
if (!is_list(xs)) {
throw new Error('reverse(xs) expects a list as argument xs, but encountered ' + xs)
}
let result = null
for (; !is_null(xs); xs = tail(xs)) {
result = pair(head(xs), result)
}
return result
}
// append first argument list and second argument list.
// In the result, the [] at the end of the first argument list
// is replaced by the second argument list
// append throws an exception if the first argument is not a list
function append(xs, ys) {
if (is_null(xs)) {
return ys
} else {
return pair(head(xs), append(tail(xs), ys))
}
}
// member looks for a given first-argument element in a given
// second argument list. It returns the first postfix sublist
// that starts with the given element. It returns [] if the
// element does not occur in the list
function member(v, xs) {
for (; !is_null(xs); xs = tail(xs)) {
if (head(xs) === v) {
return xs
}
}
return null
}
// removes the first occurrence of a given first-argument element
// in a given second-argument list. Returns the original list
// if there is no occurrence.
function remove(v, xs) {
if (is_null(xs)) {
return null
} else {
if (v === head(xs)) {
return tail(xs)
} else {
return pair(head(xs), remove(v, tail(xs)))
}
}
}
// Similar to remove. But removes all instances of v instead of just the first
function remove_all(v, xs) {
if (is_null(xs)) {
return null
} else {
if (v === head(xs)) {
return remove_all(v, tail(xs))
} else {
return pair(head(xs), remove_all(v, tail(xs)))
}
}
}
// for backwards-compatibility
// equal computes the structural equality
// over its arguments
function equal(item1, item2) {
if (is_pair(item1) && is_pair(item2)) {
return equal(head(item1), head(item2)) && equal(tail(item1), tail(item2))
} else {
return item1 === item2
}
}
// assoc treats the second argument as an association,
// a list of (index,value) pairs.
// assoc returns the first (index,value) pair whose
// index equal (using structural equality) to the given
// first argument v. Returns false if there is no such
// pair
function assoc(v, xs) {
if (is_null(xs)) {
return false
} else if (equal(v, head(head(xs)))) {
return head(xs)
} else {
return assoc(v, tail(xs))
}
}
// filter returns the sublist of elements of given list xs
// for which the given predicate function returns true.
// tslint:disable-next-line:ban-types
function filter(pred, xs) {
if (is_null(xs)) {
return xs
} else {
if (pred(head(xs))) {
return pair(head(xs), filter(pred, tail(xs)))
} else {
return filter(pred, tail(xs))
}
}
}
// enumerates numbers starting from start,
// using a step size of 1, until the number
// exceeds end.
function enum_list(start, end) {
if (typeof start !== 'number') {
throw new Error(
'enum_list(start, end) expects a number as argument start, but encountered ' + start
)
}
if (typeof end !== 'number') {
throw new Error(
'enum_list(start, end) expects a number as argument start, but encountered ' + end
)
}
if (start > end) {
return null
} else {
return pair(start, enum_list(start + 1, end))
}
}
// Returns the item in list lst at index n (the first item is at position 0)
function list_ref(xs, n) {
if (typeof n !== 'number' || n < 0 || Math.floor(n) !== n) {
throw new Error(
'list_ref(xs, n) expects a positive integer as argument n, but encountered ' + n
)
}
for (; n > 0; --n) {
xs = tail(xs)
}
return head(xs)
}
// accumulate applies given operation op to elements of a list
// in a right-to-left order, first apply op to the last element
// and an initial element, resulting in r1, then to the
// second-last element and r1, resulting in r2, etc, and finally
// to the first element and r_n-1, where n is the length of the
// list.
// accumulate(op,zero,list(1,2,3)) results in
// op(1, op(2, op(3, zero)))
function accumulate(op, initial, sequence) {
if (is_null(sequence)) {
return initial
} else {
return op(head(sequence), accumulate(op, initial, tail(sequence)))
}
}
// set_head(xs,x) changes the head of given pair xs to be x,
// throws an exception if the argument is not a pair
// LOW-LEVEL FUNCTION, NOT SOURCE
function set_head(xs, x) {
if (is_pair(xs)) {
xs[0] = x
return undefined
} else {
throw new Error('set_head(xs,x) expects a pair as argument xs, but encountered ' + xs)
}
}
// set_tail(xs,x) changes the tail of given pair xs to be x,
// throws an exception if the argument is not a pair
// LOW-LEVEL FUNCTION, NOT SOURCE
function set_tail(xs, x) {
if (is_pair(xs)) {
xs[1] = x
return undefined
} else {
throw new Error('set_tail(xs,x) expects a pair as argument xs, but encountered ' + xs)
}
}
/* end of list.js and begin of sounds.js */
// Constants
var FS = 44100; // Standard sampling rate for all problems
const fourier_expansion_level = 5; // expansion level for
// square, sawtooth, triangle
// ---------------------------------------------
// Fast reimplementations of the list library
// ---------------------------------------------
function vector_to_list(arr) {
var xs = [];
for (var i=arr.length-1; i>=0; i--) {
xs = pair(arr[i], xs);
}
return xs;
}
function list_to_vector(xs) {
var vector = [];
while(!is_null(xs)) {
vector.push(head(xs));
xs = tail(xs);
}
return vector;
}
function length(xs) {
var len = 0;
while(!is_null(xs)) {
len++;
xs = tail(xs);
}
return len;
}
function append(xs, ys) {
var v1 = list_to_vector(xs);
var v2 = list_to_vector(ys);
var vector = v1.concat(v2);
return vector_to_list(vector);
}
function map(f, xs) {
var vector = list_to_vector(xs);
for (var i=0; i<vector.length; i++) {
vector[i] = f(vector[i]);
}
return vector_to_list(vector);
}
// ---------------------------------------------
// Low-level sound support
// ---------------------------------------------
// Samples a continuous wave to a discrete waves at sampling rate for duration
// in seconds
function discretize(wave, duration) {
var vector = [];
for (var i = 0; i < duration * FS; i++) {
vector.push(wave( i / FS));
}
return vector;
}
// Discretizes a sound to a sound starting from elapsed_duration, for
// sample_length seconds
function discretize_from(wave, duration, elapsed_duration, sample_length, data) {
if (elapsed_duration + sample_length > duration) {
for (var i = elapsed_duration * FS; i < duration * FS; i++) {
data[i - elapsed_duration * FS] = wave(i / FS);
}
return data;
} else if (duration - elapsed_duration > 0) {
for (var i = elapsed_duration * FS;
i < (elapsed_duration + sample_length) * FS;
i++) {
data[i - elapsed_duration * FS] = wave(i / FS);
}
return data;
}
}
// Quantize real amplitude values into standard 4-bit PCM levels
function quantize(data) {
for (var i = 0; i < data.length; i++) {
data[i] = Math.round((data[i] + 1) * 126);
}
return data;
}
// Try to eliminate clicks by smoothening out sudden jumps at the end of a wave
function simple_filter(data) {
for (var i = 0; i < data.length; i++) {
if (data[i] > 1) {
data[i] = 1;
}
if (data[i] < -1) {
data[i] = -1;
}
}
var old_value = 0;
for (var i = 0; i < data.length; i++) {
if (Math.abs(old_value - data[i]) > 0.01 && data[i] == 0) {
data[i] = old_value * 0.999;
}
old_value = data[i];
}
return data;
}
function copy(data) {
var ret = [];
for (var i = 0; i < data.length; i++) {
ret[i] = data[i];
}
return ret;
}
// Raw data to html5 audio element
function raw_to_audio(_data) {
data = copy(_data);
data = simple_filter(data);
data = quantize(data);
var riffwave = new RIFFWAVE();
riffwave.header.sampleRate = FS;
riffwave.header.numChannels = 1;
riffwave.Make(data);
var audio = new Audio(riffwave.dataURI);
return audio;
}
// ---------------------------------------------
// Source API for Students
// ---------------------------------------------
// Data abstractions:
// time: real value in seconds x > 0
// amplitude: real value -1 <= x <= 1
// duration: real value in seconds 0 < x < Infinity
// sound: (time -> amplitude) x duration
/**
* Makes a sound from a wave and a duration.
* The wave is a function from time (in seconds)
* to an amplitude value that should lie between
* -1 and 1. The duration is given in seconds.
* @param {function} wave - given wave function
* @param {number} duration - in seconds
* @returns {sound}
*/
function make_sound(wave, duration) {
return pair(t => t >= duration ? 0 : wave(t), duration);
}
/**
* Accesses the wave of a sound.
* The wave is a function from time (in seconds)
* to an amplitude value that should lie between
* -1 and 1.
* @param {sound} sound - given sound
* @returns {function} wave function of the sound
*/
function get_wave(sound) {
return head(sound);
}
/**
* Accesses the duration of a sound, in seconds.
* @param {sound} sound - given sound
* @returns {number} duration in seconds
*/
function get_duration(sound) {
return tail(sound);
}
/**
* Checks if a given value is a sound
* @param {value} x - given value
* @returns {boolean} whether <CODE>x</CODE> is a sound
*/
function is_sound(x) {
return is_pair(x) &&
((typeof get_wave(x)) === 'function') &&
((typeof get_duration(x)) === 'number');
}
// Keeps track of whether play() is currently running,
// and the current audio context.
var _playing = false;
var _player;
function play_unsafe(sound) {
// type-check sound
if ( !is_sound(sound) ) {
throw new Error("play is expecting sound, but encountered " + sound);
}
// Declaring duration and wave variables
var wave = get_wave(sound);
var duration = get_duration(sound);
// If a sound is already playing, terminate execution
if (_playing) {
throw new Error("play: audio system still playing previous sound");
}
_playing = true;
// Create AudioContext (test this out might fix safari issue)
//const AudioContext = window.AudioContext || window.webkitAudioContext;
// Main audio context
_player = new AudioContext();
// Controls Length of buffer in seconds.
var buffer_length = 0.1;
// Define Buffer Size
var bufferSize = FS * buffer_length;
// Create two buffers
var buffer1 = _player.createBuffer(1, bufferSize, FS);
var buffer2 = _player.createBuffer(1, bufferSize, FS);
// Keep track of elapsed_duration & first run of ping_pong
var elapsed_duration = 0;
var first_run = true;
// Schedules playback of sounds
function ping_pong(current_sound, next_sound, current_buffer, next_buffer) {
// If sound has exceeded duration, early return to stop calls.
if (elapsed_duration > duration || !_playing) {
stop();
return;
}
// Fill current_buffer, then play current_sound.
if (first_run) {
// No longer first run of ping_pong.
first_run = false;
// Discretize first chunk, load into current_buffer.
let current_data = current_buffer.getChannelData(0);
current_data = discretize_from(wave, duration, elapsed_duration,
buffer_length, current_data);
// Create current_sound.
current_sound = new AudioBufferSourceNode(_player);
// Set current_sound's buffer to current_buffer.
current_sound.buffer = current_buffer;
// Play current_sound.
current_sound.connect(_player.destination);
current_sound.start();
// Increment elapsed duration.
elapsed_duration += buffer_length;
}
// Fill next_buffer while current_sound is playing,
// schedule next_sound to play after current_sound terminates.
// Discretize next chunk, load into next_buffer.
let next_data = next_buffer.getChannelData(0);
next_data = discretize_from(wave, duration, elapsed_duration,
buffer_length, next_data);
// Create next_sound.
next_sound = new AudioBufferSourceNode(_player);
// Set next_sound's buffer to next_buffer.
next_sound.buffer = next_buffer;
// Schedule next_sound to play after current_sound.
next_sound.connect(_player.destination);
next_sound.start(start_time + elapsed_duration);
// Increment elapsed duration.
elapsed_duration += buffer_length;
current_sound.onended =
event =>
ping_pong(next_sound, current_sound, next_buffer, current_buffer);
}
var start_time = _player.currentTime;
ping_pong(null, null, buffer1, buffer2);
return sound;
}
// "Safe" playing for overly complex sounds.
// Discretizes full sound before playing
// (i.e. plays sound properly, but possibly with
// a delay).
var _safeplaying = false;
var _safeaudio = null;
/**
* plays a given sound using your computer's sound device
* @param {sound} sound - given sound
* @returns {undefined} undefined
*/
function play(sound) {
// If a sound is already playing, terminate execution.
if (_safeplaying || _playing) return;
// Discretize the input sound
var data = discretize(get_wave(sound), get_duration(sound));
_safeaudio = raw_to_audio(data);
_safeaudio.addEventListener('ended', stop);
_safeaudio.play();
_safeplaying = true;
}
/* sound_to_string and string_to_sound would be really cool!!!
function sound_to_string(sound) {
let discretized_wave = discretize(wave(sound), duration(sound));
let discretized_sound = pair(discretized_wave, duration(sound));
return stringify(pair(data), tail(sound));
}
function string_to_sound(str) {
var discretized_sound = eval(str);
return pair(t => ..., duration(data));
}
*/
/**
* Stops playing the current sound
* @returns {undefined} undefined
*/
function stop() {
// If using normal play()
if (_playing) {
_player.close();
}
// If using play_safe()
if (_safeplaying) {
_safeaudio.pause();
_safeaudio = null;
}
_playing = false;
_safeplaying = false;
}
// Concats a list of sounds
/**
* makes a new sound by combining the sounds in a given
* list so that
* they play consecutively, each next sound starting when the
* previous sound ends
* @param {list_of_sounds} sounds - given list of sounds
* @returns {sound} resulting sound
*/
function consecutively(list_of_sounds) {
function consec_two(ss1, ss2) {
var wave1 = head(ss1);
var wave2 = head(ss2);
var dur1 = tail(ss1);
var dur2 = tail(ss2);
var new_wave = t => t < dur1 ? wave1(t) : wave2(t - dur1);
return pair(new_wave, dur1 + dur2);
}
return accumulate(consec_two, silence_sound(0), list_of_sounds);
}
// Mushes a list of sounds together
/**
* makes a new sound by combining the sounds in a given
* list so that
* they play simutaneously, all starting at the beginning of the
* resulting sound
* @param {list_of_sounds} sounds - given list of sounds
* @returns {sound} resulting sound
*/
function simultaneously(list_of_sounds) {
function musher(ss1, ss2) {
var wave1 = head(ss1);
var wave2 = head(ss2);
var dur1 = tail(ss1);
var dur2 = tail(ss2);
// new_wave assumes sound discipline (ie, wave(t) = 0 after t > dur)
var new_wave = t => wave1(t) + wave2(t);
// new_dur is higher of the two dur
var new_dur = dur1 < dur2 ? dur2 : dur1;
return pair(new_wave, new_dur);
}
var mushed_sounds = accumulate(musher, silence_sound(0), list_of_sounds);
var normalised_wave = t =>
(head(mushed_sounds))(t) / length(list_of_sounds);
var highest_duration = tail(mushed_sounds);
return pair(normalised_wave, highest_duration);
}
/**
* makes a sound of a given duration by randomly
* generating amplitude values
* @param {number} duration - duration of result sound, in seconds
* @returns {sound} resulting noise sound
*/
function noise_sound(duration) {
return make_sound(t => Math.random() * 2 - 1, duration);
}
/**