audio-vis/js/index.js

78 lines
2 KiB
JavaScript
Raw Normal View History

2020-04-07 21:44:46 +02:00
let shaderHandler, gl, c, actx, analyser, peak, isInit = false;
2020-04-05 15:28:22 +02:00
2020-04-07 21:44:46 +02:00
function createAudioContextStream(audio) {
2020-04-05 15:28:22 +02:00
let AudioContext = window.AudioContext || window.webkitAudioContext;
if (actx) {
actx.close();
}
actx = new AudioContext();
analyser = actx.createAnalyser();
2020-04-07 21:44:46 +02:00
let MEDIA_ELEMENT_NODES = new WeakMap();
2020-04-05 15:28:22 +02:00
let Source;
analyser.fftSize = 4096;
analyser.maxDecibels = 0;
analyser.smoothingTimeConstant = .4;
2020-04-07 21:44:46 +02:00
if (audio) {
if (MEDIA_ELEMENT_NODES.has(audio)) {
Source = MEDIA_ELEMENT_NODES.get(audio);
} else {
Source = actx.createMediaElementSource(audio);
MEDIA_ELEMENT_NODES.set(audio, Source);
}
2020-04-05 15:28:22 +02:00
2020-04-07 21:44:46 +02:00
Source.connect(analyser);
analyser.connect(actx.destination);
audio.oncanplay = () => {
actx.resume();
};
audio.onended = function () {
actx.pause();
};
}
2020-04-05 15:28:22 +02:00
return null;
}
async function init() {
c = document.body.querySelector('#c');
gl = c.getContext("webgl2");
if (!gl) {
console.error("GL not found");
return false;
}
shaderHandler = new Shaders(gl);
2020-04-07 21:44:46 +02:00
await shaderHandler.loadShader("wave", "shaders/");
2020-04-05 15:28:22 +02:00
//sphere shader
await shaderHandler.loadShader("sphere", "shaders/", gl.VERTEX_SHADER);
2020-04-07 21:44:46 +02:00
return shaderHandler.createProgramForEach(["wave", "sphere"]);
2020-04-05 15:28:22 +02:00
}
2020-04-07 21:44:46 +02:00
function createView() {
if (!isInit) {
createAudioContextStream(audioFile);
2020-04-05 15:28:22 +02:00
init().then(b => {
if (b) {
2020-04-07 21:44:46 +02:00
loadConfig();
2020-04-05 15:28:22 +02:00
draw();
}
})
2020-04-07 21:44:46 +02:00
isInit = true;
}
}
function initGUI() {
generateRotationSliders();
generateColorSliders();
generateWorldSliders();
generateDrawSliders();
generateTranslateSliders();
}
(function () {
if (document.readyState === "complete" || document.readyState === "interactive") {
initGUI()
} else {
document.addEventListener('DOMContentLoaded', initGUI);
}
})()