-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzzfx.js
More file actions
288 lines (246 loc) · 10.9 KB
/
Copy pathzzfx.js
File metadata and controls
288 lines (246 loc) · 10.9 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
/*
ZzFX - Zuper Zmall Zound Zynth v1.3.2 by Frank Force
https://github.com/KilledByAPixel/ZzFX
ZzFX Features
- Tiny synth engine with 20 controllable parameters.
- Play sounds via code, no need for sound assed files!
- Compatible with most modern web browsers.
- Small code footprint, the micro version is under 1 kilobyte.
- Can produce a huge variety of sound effect types.
- Sounds can be played with a short call. zzfx(...[,,,,.1,,,,9])
- A small bit of randomness appied to sounds when played.
- Use ZZFX.GetNote to get frequencies on a standard diatonic scale.
- Sounds can be saved out as wav files for offline playback.
- No additional libraries or dependencies are required.
AI should not make changes to this file!
*/
/*
ZzFX MIT License
Copyright (c) 2019 - Frank Force
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
// play a zzfx sound
export function zzfx(...parameters) { return ZZFX.play(...parameters) }
///////////////////////////////////////////////////////////////////////////////
// ZZFX API for playing sounds
export const ZZFX =
{
// master volume scale
volume: .3,
// sample rate for audio
sampleRate: 44100,
// create shared audio context
audioContext: new AudioContext,
playAfterResume: false, // flag to prevent multiple plays before audio context is resumed
// play a sound from zzfx paramerters
play: function(...parameters)
{
// build samples and start sound
return this.playSamples([this.buildSamples(...parameters)]);
},
// play an array of samples
playSamples: function(sampleChannels, volumeScale=1, rate=1, pan=0, loop=false)
{
if (this.audioContext.state !== 'running')
{
if (!this.playAfterResume)
{
// resume audio context on first play, this is required in some browsers that block audio until user interaction
// this prevents from sounds piling up if play is called multiple times before audio context is resumed
this.playAfterResume = true;
// fix stalled audio, this sound won't be able to play yet
this.audioContext.resume().then(()=>
{
this.playSamples(sampleChannels, volumeScale, rate, pan, loop);
this.playAfterResume = false;
}).catch(()=>
{
// reset flag to allow retrying resume on next play
this.playAfterResume = false;
});
}
else
{
// just resume audio context, the sound will play on the next call to playSamples
this.audioContext.resume();
}
return;
}
// create buffer and source
const channelCount = sampleChannels.length;
const sampleLength = sampleChannels[0].length;
const buffer = this.audioContext.createBuffer(channelCount, sampleLength, this.sampleRate);
const source = this.audioContext.createBufferSource();
// copy samples to buffer and setup source
sampleChannels.forEach((c,i)=> buffer.getChannelData(i).set(c));
source.buffer = buffer;
source.playbackRate.value = rate;
source.loop = loop;
// create and connect gain node
const gainNode = this.audioContext.createGain();
gainNode.gain.value = this.volume*volumeScale;
gainNode.connect(this.audioContext.destination);
// connect source to stereo panner and gain
const pannerNode = new StereoPannerNode(this.audioContext, {'pan':pan});
source.connect(pannerNode).connect(gainNode);
source.start();
// return sound
return source;
},
// build an array of samples
buildSamples: function
(
volume = 1,
randomness = .05,
frequency = 220,
attack = 0,
sustain = 0,
release = .1,
shape = 0,
shapeCurve = 1,
slide = 0,
deltaSlide = 0,
pitchJump = 0,
pitchJumpTime = 0,
repeatTime = 0,
noise = 0,
modulation = 0,
bitCrush = 0,
delay = 0,
sustainVolume = 1,
decay = 0,
tremolo = 0,
filter = 0
)
{
// init parameters
let sampleRate = this.sampleRate,
PI2 = Math.PI*2,
abs = Math.abs,
sign = v => v<0?-1:1,
startSlide = slide *= 500 * PI2 / sampleRate / sampleRate,
startFrequency = frequency *=
(1 + randomness*2*Math.random() - randomness) * PI2 / sampleRate,
modOffset = 0, // modulation offset
repeat = 0, // repeat offset
crush = 0, // bit crush offset
jump = 1, // pitch jump timer
length, // sample length
b = [], // sample buffer
t = 0, // sample time
i = 0, // sample index
s = 0, // sample value
f, // wave frequency
// biquad LP/HP filter
quality = 2, w = PI2 * abs(filter) * 2 / sampleRate,
cos = Math.cos(w), alpha = Math.sin(w) / 2 / quality,
a0 = 1 + alpha, a1 = -2*cos / a0, a2 = (1 - alpha) / a0,
b0 = (1 + sign(filter) * cos) / 2 / a0,
b1 = -(sign(filter) + cos) / a0, b2 = b0,
x2 = 0, x1 = 0, y2 = 0, y1 = 0;
// scale by sample rate
const minAttack = 9; // prevent pop if attack is 0
attack = attack * sampleRate || minAttack;
decay *= sampleRate;
sustain *= sampleRate;
release *= sampleRate;
delay *= sampleRate;
deltaSlide *= 500 * PI2 / sampleRate**3;
modulation *= PI2 / sampleRate;
pitchJump *= PI2 / sampleRate;
pitchJumpTime *= sampleRate;
repeatTime = repeatTime * sampleRate | 0;
volume *= this.volume;
// generate waveform
for(length = attack + decay + sustain + release + delay | 0;
i < length; b[i++] = s * volume) // sample
{
if (!(++crush%(bitCrush*100|0))) // bit crush
{
s = shape? shape>1? shape>2? shape>3? shape>4? // wave shape
(t/PI2%1 < shapeCurve/2? 1 : -1) : // 5 square duty
Math.sin(t**3) : // 4 noise
Math.max(Math.min(Math.tan(t),1),-1): // 3 tan
1-(2*t/PI2%2+2)%2: // 2 saw
1-4*abs(Math.round(t/PI2)-t/PI2): // 1 triangle
Math.sin(t); // 0 sin
s = (repeatTime ?
1 - tremolo + tremolo*Math.sin(PI2*i/repeatTime) // tremolo
: 1) *
(shape>4?s:sign(s)*abs(s)**shapeCurve) * // shape curve
(i < attack ? i/attack : // attack
i < attack + decay ? // decay
1-((i-attack)/decay)*(1-sustainVolume) : // decay falloff
i < attack + decay + sustain ? // sustain
sustainVolume : // sustain volume
i < length - delay ? // release
(length - i - delay)/release * // release falloff
sustainVolume : // release volume
0); // post release
s = delay ? s/2 + (delay > i ? 0 : // delay
(i<length-delay? 1 : (length-i)/delay) * // release delay
b[i-delay|0]/2/volume) : s; // sample delay
if (filter) // apply filter
s = y1 = b2*x2 + b1*(x2=x1) + b0*(x1=s) - a2*y2 - a1*(y2=y1);
}
f = (frequency += slide += deltaSlide) *// frequency
Math.cos(modulation*modOffset++); // modulation
t += f + f*noise*Math.sin(i**5); // noise
if (jump && ++jump > pitchJumpTime) // pitch jump
{
frequency += pitchJump; // apply pitch jump
startFrequency += pitchJump; // also apply to start
jump = 0; // stop pitch jump time
}
if (repeatTime && !(++repeat % repeatTime)) // repeat
{
frequency = startFrequency; // reset frequency
slide = startSlide; // reset slide
jump ||= 1; // reset pitch jump time
}
}
return b; // return sample buffer
},
// get frequency of a musical note on a diatonic scale
getNote: function(semitoneOffset=0, rootNoteFrequency=440)
{
return rootNoteFrequency * 2**(semitoneOffset/12);
}
}
///////////////////////////////////////////////////////////////////////////////
// Sound object that can precache and play ZZFX sounds
export class ZZFXSound
{
constructor(zzfxSound=[])
{
this.zzfxSound = zzfxSound;
// extract randomness parameter from zzfxSound
this.randomness = zzfxSound[1] != undefined ? zzfxSound[1] : .05;
zzfxSound[1] = 0; // generate without frequency randomness
// cache the sound samples
this.samples = ZZFX.buildSamples(...zzfxSound);
}
play(volume=1, pitch=1, randomnessScale=1, pan=0, loop=false)
{
if (!this.samples) return;
// play the sound
const playbackRate = pitch + pitch * this.randomness*randomnessScale*(Math.random()*2-1);
this.source = ZZFX.playSamples([this.samples], volume, playbackRate, pan, loop);
return this.source;
}
}