Scorch/static/scorch.js
2020-05-11 12:41:26 -04:00

74 lines
1.9 KiB
JavaScript

var socket;
var audioCtx = new window.AudioContext();
var source = audioCtx.createBufferSource();
var total_raw;
function appendBuffer(buffer1, buffer2) {
let numberOfChannels = Math.min( buffer1.numberOfChannels, buffer2.numberOfChannels );
let tmp = audioCtx.createBuffer( numberOfChannels, (buffer1.length + buffer2.length), buffer1.sampleRate );
for (let i=0; i<numberOfChannels; i++) {
let channel = tmp.getChannelData(i);
channel.set( buffer1.getChannelData(i), 0);
channel.set( buffer2.getChannelData(i), buffer1.length);
}
return tmp;
}
function appendBuffer2(buffer1, buffer2) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
var buff1 = new Uint8Array(buffer1);
var buff2 = new Uint8Array(buffer2);
tmp.set(buff1, 0);
tmp.set(buff2, buffer1.byteLength);
return tmp.buffer;
};
function load() {
socket = init_websocket();
}
/* Websocket setup */
function init_websocket() {
let socket = new WebSocket('wss://' + window.location.hostname + ws_uri);
socket.binaryType = "arraybuffer";
socket.onmessage = onmessage;
socket.onclose = onclose;
socket.onerror = onerror;
socket.events = {};
return socket;
}
function onmessage (e) {
console.log(e);
if (e.data.constructor === ArrayBuffer) {
console.log(e.data.byteLength);
if (source.buffer != null) {
total_raw = appendBuffer2(total_raw, e.data);
} else {
total_raw = e.data;
}
audioCtx.decodeAudioData(total_raw.slice(0)).then(function(decodedBuffer) {
if (source.buffer != null) {
source.stop();
}
source = audioCtx.createBufferSource();
source.buffer = decodedBuffer;
source.connect(audioCtx.destination);
source.start(0, audioCtx.currentTime);
});
}
}
function onclose(e) {
if (e.wasClean) { return; } // no need to reconnect
console.log(e);
console.log('Websocket lost connection to server. Re-trying...');
//socket = init_websocket();
//await sleep(5000);
}
function onerror(e) {
console.log("Websocket error!")
console.log(e);
}