This repository has been archived by the owner on Sep 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
116 lines (84 loc) · 2.1 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
/**
* @module audio-table
*/
module.exports = {
sin: sin,
cos: cos,
saw: saw,
triangle: triangle,
square: square,
delta: delta,
pulse: pulse,
noise: noise,
// wave: require('./wave')
// scale: require('./scale')
fill: fill
};
var pi2 = Math.PI * 2;
function noise (arg) {
return fill(arg, function (val) {
return Math.random() * 2 - 1;
})
};
function triangle (arg, scale) {
if (scale == null) scale = 0.5;
return fill(arg, function (val, i, data) {
var l = data.length;
var l2 = l / 2;
var l2scale = l2 * scale;
if (i < l2scale) return i / l2scale;
if (i < l - l2scale) return 1 - (i - l2scale) * 2 / (l - l2);
return 1 - (i - l - l2scale) / (l - l - l2scale);
});
};
function cos (arg, wavenumber) {
if (wavenumber == null) wavenumber = 1;
return fill(arg, function(val, i, data) {
return Math.cos(Math.PI * 2 * wavenumber * i / data.length)
});
};
function sin (arg, wavenumber) {
if (wavenumber == null) wavenumber = 1;
return fill(arg, function(val, i, data) {
return Math.sin(Math.PI * 2 * wavenumber * i / data.length)
});
};
function delta (arg) {
return fill(arg, function(val, i, data) {
return i === 0 ? 1 : 0;
});
};
function pulse (arg, weight) {
if (weight == null) weight = 0;
return fill(arg, function(val, i, data) {
return i < Math.max(data.length * weight, 1) ? 1 : -1;
});
}
function square (arg) {
return pulse(arg, 0.5);
};
function saw (arg) {
return fill(arg, function(val, i, data) {
return 1 - 2 * i / (data.length - 1);
});
};
/**
* Fill passed array or create array and fill with the function
* From the start/end positions
*/
function fill (arg, fn, start, end) {
var table = getList(arg);
if (start == null) start = 0;
else if (start < 0) start += table.length;
if (end == null) end = table.length;
else if (end < 0) end += table.length;
for (var i = start; i < end; i++) {
table[i] = fn(table[i], i, table);
}
return table;
};
function getList (arg) {
if (!arg) throw Error('Cannot create undefined wavetable. Please, pass the number or Array')
if (arg.length != null) return arg;
else return new Float32Array(arg)
};