-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscript.js
449 lines (405 loc) · 17.5 KB
/
script.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
// TUNING PERFORMANCE
var audio1;
var worker;
var canvas = document.getElementById("canvas").transferControlToOffscreen();
var audioEl = document.getElementById('audio')
var container = document.getElementById('container')
var local_stream= null
var source = null
var audioCtx = null
const normalize = (val, threshold=200) => ((val > threshold) ? val - threshold : 0);
const normalize1 = (val, max, min) => ((val-min)/(max-min))
canvas.width = window.innerWidth
canvas.height = window.innerHeight
var defaultState= {
radius: 128,
color: '#000000',
showParticles: true,
displayType: 11,
bufferLength: 128,
fftSize: 2**14,
bounceMultiplier: 250,
beatDetection: true,
bounce: 0
}
if (!navigator.getUserMedia)
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia;
var config= {...defaultState}
function upload_audio(e, file=false) {
config = {...defaultState}
if(file) {
var file = e.target.files[0]
var reader = new FileReader();
if(local_stream) local_stream.getAudioTracks()[0].enabled = false;
reader.onload = async function(evt) {
url = evt.target.result;
if(!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // for safari browser // I need to explain the browser restrictions & CORS issues here
}
// let origblob = new Blob(, { type: file.type });// The blob gives us a URL to the video file:
// var arrayBuffer = await new Response(origblob).arrayBuffer();
let audioBuffer = await audioCtx.decodeAudioData(url);
let audioBlob = convertAudioBufferToBlob(audioBuffer)// The blob gives us a URL to the video file:
url = window.URL.createObjectURL(audioBlob);
audioEl.pause()
audioEl.src = url
if(!worker){
worker = new Worker(new URL("./worker.js", window.location));
worker.postMessage({ canvas }, [canvas]);
}
let analyser = null;
let filter = audioCtx.createBiquadFilter();// creates an filter node from the audio source
filter.type = 'highshelf'
filter.gain.value = 10
filter.frequency.value = 400;
// var gainNode = audioCtx.createGain()
if(!source){
source = audioCtx.createMediaElementSource(audioEl)
}
analyser = audioCtx.createAnalyser();
source.connect(analyser)
// lowpass.connect(highpass)
source.connect(audioCtx.destination)
// lowpass.type = "lowpass"
// lowpass.frequency.value = 200
// lowpass.gain.value = -1
// highpass.type = "highpass"
// highpass.frequency.value = 10
// highpass.gain.value = -1
// highpass.connect(analyser)
analyser.fftSize = defaultState.fftSize // controls the size of the FFT. The FFT is a fast fourier transform. Basically the number of sound samples. Will be used to draw bars in the canvas
// const bufferLength = analyser.frequencyBinCount; // the number of data values that dictate the number of bars in the canvas. Always exactly one half of the fft size
const bufferLength = defaultState.bufferLength;
const dataArray = new Uint8Array(bufferLength); // coverting to unsigned 8-bit integer array format because that's the format we need
function animate() {
analyser.getByteFrequencyData(dataArray); // copies the frequency data into the dataArray in place. Each item contains a number between 0 and 255
const setBounce = ()=>{
let bassArr = dataArray.slice(0,config.bufferLength)
let max = Math.max(...bassArr)
let min = Math.min(...bassArr)
let threshold2 = min+ (max-min)*0.7
let newNorm = bassArr.map(val=>normalize(val, threshold2))
let threshold1 = newNorm.reduce((acc,crr)=>acc+crr/bassArr.length,0)
let bounce = threshold1 * 0.01
let bounced =defaultState.radius + Math.floor(bounce*defaultState.bounceMultiplier)
let height =bounced*2>window.innerHeight ?window.innerHeight/2:bounced
let width =bounced*2>window.innerWidth ?window.innerWidth/2:bounced
config.radius = Math.min(height,width)
config.bounce = bounce
}
const setLogo = ()=>{
let logoExists = container.querySelector('.logo_img')
if(logoExists) {
logoExists.height = config.radius *2
logoExists.width = config.radius *2
}
}
setBounce()
worker.postMessage({ bufferLength, dataArray, config }, {});
setTimeout(setLogo,500)
requestAnimationFrame(animate); // calls the animate function again. This method is built in
}
animate();
};
reader.readAsArrayBuffer(file);
}
else {
if (navigator.getUserMedia){
// local_stream.getAudioTracks()[0].enabled = true;
navigator.getUserMedia({audio:true}, async function(stream){
local_stream = stream
url = stream
const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // for safari browser // I need to explain the browser restrictions & CORS issues here
if(!worker){
worker = new Worker(new URL("./worker.js", window.location));
worker.postMessage({ canvas }, [canvas]);
}
audioEl.src= ''
let analyser = null;
let source = audioCtx.createMediaStreamSource(url)
analyser = audioCtx.createAnalyser();
source.connect(analyser)
analyser.fftSize = defaultState.fftSize // controls the size of the FFT. The FFT is a fast fourier transform. Basically the number of sound samples. Will be used to draw bars in the canvas
const bufferLength = defaultState.bufferLength;
const dataArray = new Uint8Array(bufferLength); // coverting to unsigned 8-bit integer array format because that's the format we need
function animate() {
analyser.getByteFrequencyData(dataArray);
const setBounce = ()=>{
let max = Math.max(...dataArray.slice(0,config.bufferLength/2))
let bounce =normalize1(max,255,0);
let bounced =defaultState.radius + Math.floor(bounce*defaultState.bounceMultiplier)
let height =bounced*2>window.innerHeight ?window.innerHeight/2:bounced
let width =bounced*2>window.innerWidth ?window.innerWidth/2:bounced
config.radius = Math.min(height,width)
config.bounce = bounce
}
const setLogo = ()=>{
let logoExists = container.querySelector('.logo_img')
if(logoExists) {
logoExists.height = config.radius *2
logoExists.width = config.radius *2
}
}
setBounce()
worker.postMessage({ bufferLength, dataArray, config }, {});
setTimeout(setLogo,250)
requestAnimationFrame(animate); // calls the animate function again. This method is built in
}
animate();
},function(e) {
alert('Error capturing audio.');
})
}
}
}
/*basic*/
document.getElementById('upload_bg').addEventListener('change', function(e) {
var file = this.files[0]
var reader = new FileReader();
reader.onload = function(evt) {
url = evt.target.result;
if(file.type.startsWith('image')){
let videoExists = container.querySelector('video')
if(videoExists){
container.removeChild(videoExists)
}
container.style = `background-image: url(${url}); background-repeat:no-repeat;background-size:contain;background-position:center;`
} else {
let videoBlob = new Blob([new Uint8Array(url)], { type: file.type });// The blob gives us a URL to the video file:
url = window.URL.createObjectURL(videoBlob);
const videoElem = document.createElement('video')
var sourceMP4 = document.createElement("source");
sourceMP4.type = file.type;
sourceMP4.src = url;
videoElem.appendChild(sourceMP4);
let videoExists = container.querySelector('video')
if(videoExists){
container.removeChild(videoExists)
}
container.style = `background-image:none`
videoElem.style="position: absolute;object-fit: cover;width: 100vw;height: 100vh;z-index: -1;left: 0;right: 0;top: 0;bottom: 0;"
videoElem.autoplay = true
videoElem.muted = true
videoElem.loop = true
container.appendChild(videoElem)
}
}
if(file.type.startsWith('image')){
reader.readAsDataURL(file);
} else {
reader.readAsArrayBuffer(file)
}
})
document.getElementById('upload_logo').addEventListener('change', function(e) {
var file = this.files[0]
var reader = new FileReader();
reader.onload = function(evt) {
url = evt.target.result;
const logo_img = document.createElement('img')
logo_img.src = url;
logo_img.width=config.radius * 2
logo_img.height=config.radius * 2
logo_img.classList.add('logo_img')
logo_img.style = 'position:absolute;'
let logoExists = container.querySelector('.logo_img')
if(logoExists){
container.removeChild(logoExists)
}
container.appendChild(logo_img)
}
reader.readAsDataURL(file);
})
document.getElementById('stroke_color').addEventListener('change', function(e) {
var stroke_color = e.target.value
config.color = stroke_color
})
document.addEventListener("keydown", (e) => {
if (e.key === " ") {
e.preventDefault()
audioEl.paused ? audio.play() : audio.pause();
}
})
container.addEventListener('click',(e)=>{
audioEl.paused ? audio.play() : audio.pause();
})
function showAudiocontrols(){
document.getElementById('container-config').style.visibility='visible'
container.style.cursor='auto'
}
function hideAudiocontrols(){
document.getElementById('container-config').style.visibility='hidden'
container.style.cursor='none'
}
var timer = null
container.addEventListener('mousemove',()=>{
clearTimeout(timer)
showAudiocontrols()
timer = setTimeout(()=>{
hideAudiocontrols()
},3000)
})
document.getElementById('fullscreen').addEventListener('click',toggleFullScreen)
function cancelFullScreen() {
var el = document;
var requestMethod = el.cancelFullScreen||el.webkitCancelFullScreen||el.mozCancelFullScreen||el.exitFullscreen||el.webkitExitFullscreen;
if (requestMethod) { // cancel full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return false
}
function toggleFullScreen(e) {
e.stopPropagation();
el = document.body; // Make the body go full screen.
var isInFullScreen = (document.fullScreenElement && document.fullScreenElement !== null) || (document.mozFullScreen || document.webkitIsFullScreen);
let img = document.getElementById('fullscreen').querySelector('img')
if (isInFullScreen) {
img.src = '/img/fullscreen.png'
cancelFullScreen();
} else {
img.src = '/img/exitscreen.png'
requestFullScreen(el);
}
}
function displayChange(event){
let val = event.target.value
defaultState.displayType = parseInt(val)
config.displayType = parseInt(val)
}
function radiusChange(event){
let val = event.target.value
let logoExists = container.querySelector('.logo_img')
let width = val*2>window.innerWidth ?window.innerWidth/2: val
let height = val*2>window.innerHeight ?window.innerHeight/2: val
defaultState.radius = Math.min(height,width)
if(logoExists) {
logoExists.height = defaultState.radius *2
logoExists.width = defaultState.radius * 2
}
}
function setFFTSize(event){
let val = event.target.value
defaultState.fftSize = Math.pow(2,parseInt(val))
config.fftSize = Math.pow(2,parseInt(val))
}
function setBufferLength(event){
let val = event.target.value
defaultState.bufferLength = parseInt(val)
config.bufferLength = parseInt(val)
}
function setBeatDetection(event){
let val = event.target.value === 'true'
defaultState.beatDetection = Boolean(val)
config.beatDetection = Boolean(val)
}
function setBounceMultiplier(event){
let val = event.target.value
defaultState.bounceMultiplier = parseInt(val)
config.bounceMultiplier = parseInt(val)
}
function setShowParticles(event){
let val = event.target.value === 'true'
defaultState.showParticles = val
config.showParticles = val
}
//utility
function convertAudioBufferToBlob(audioBuffer) {
// Float32Array samples
const [left, right] = [audioBuffer.getChannelData(0), audioBuffer.getChannelData(1)]
// interleaved
const interleaved = new Float32Array(left.length + right.length)
for (let src=0, dst=0; src < left.length; src++, dst+=2) {
interleaved[dst] = left[src]
interleaved[dst+1] = right[src]
}
// get WAV file bytes and audio params of your audio source
const wavBytes = getWavBytes(interleaved.buffer, {
isFloat: true, // floating point or 16-bit integer
numChannels: 2,
sampleRate: 48000,
})
const wav = new Blob([wavBytes], { type: 'audio/wav' })
return wav
}
// Returns Uint8Array of WAV bytes
function getWavBytes(buffer, options) {
const type = options.isFloat ? Float32Array : Uint16Array
const numFrames = buffer.byteLength / type.BYTES_PER_ELEMENT
const headerBytes = getWavHeader(Object.assign({}, options, { numFrames }))
const wavBytes = new Uint8Array(headerBytes.length + buffer.byteLength);
// prepend header, then add pcmBytes
wavBytes.set(headerBytes, 0)
wavBytes.set(new Uint8Array(buffer), headerBytes.length)
return wavBytes
}
// adapted from https://gist.github.com/also/900023
// returns Uint8Array of WAV header bytes
function getWavHeader(options) {
const numFrames = options.numFrames
const numChannels = options.numChannels || 2
const sampleRate = options.sampleRate || 44100
const bytesPerSample = options.isFloat? 4 : 2
const format = options.isFloat? 3 : 1
const blockAlign = numChannels * bytesPerSample
const byteRate = sampleRate * blockAlign
const dataSize = numFrames * blockAlign
const buffer = new ArrayBuffer(44)
const dv = new DataView(buffer)
let p = 0
function writeString(s) {
for (let i = 0; i < s.length; i++) {
dv.setUint8(p + i, s.charCodeAt(i))
}
p += s.length
}
function writeUint32(d) {
dv.setUint32(p, d, true)
p += 4
}
function writeUint16(d) {
dv.setUint16(p, d, true)
p += 2
}
writeString('RIFF') // ChunkID
writeUint32(dataSize + 36) // ChunkSize
writeString('WAVE') // Format
writeString('fmt ') // Subchunk1ID
writeUint32(16) // Subchunk1Size
writeUint16(format) // AudioFormat https://i.stack.imgur.com/BuSmb.png
writeUint16(numChannels) // NumChannels
writeUint32(sampleRate) // SampleRate
writeUint32(byteRate) // ByteRate
writeUint16(blockAlign) // BlockAlign
writeUint16(bytesPerSample * 8) // BitsPerSample
writeString('data') // Subchunk2ID
writeUint32(dataSize) // Subchunk2Size
return new Uint8Array(buffer)
}
window.addEventListener('resize', () => {
if (worker) {
let height = defaultState.radius*2>window.innerHeight ?window.innerHeight/2: defaultState.radius
let width = defaultState.radius*2>window.innerWidth ?window.innerWidth/2: defaultState.radius
config.radius = Math.min(height,width)
let resize_canvas = [window.innerWidth, window.innerHeight]
maxDistributionX = window.innerWidth / 8;
maxDistributionY = window.innerHeight / 4;
worker.postMessage({ resize_canvas })
}
})