setup audio receiver and event dispatcher

This commit is contained in:
Lewis Moten
2024-05-11 03:33:40 -04:00
parent fdb6723e87
commit 6647e5b51d
6 changed files with 376 additions and 279 deletions

View File

@@ -1,3 +1,7 @@
import Dispatcher from "./Dispatcher";
const dispatcher = new Dispatcher('AudioSender', ['begin', 'end', 'send']);
let audioContext;
let CHANNELS = [];
let DESTINATION;
@@ -9,6 +13,9 @@ let WAVE_FORM;
let stopOscillatorsTimeoutId;
export const addEventListener = dispatcher.addListener;
export const removeEventListener = dispatcher.removeListener;
export const changeConfiguration = ({
channels,
destination,
@@ -58,7 +65,7 @@ export function beginAt(streamStartSeconds) {
oscillator.start(streamStartSeconds);
oscillators.push(oscillator);
}
callFn(ON_START);
dispatcher.emit('begin');
return oscillators;
}
function getOscillators() {
@@ -66,10 +73,11 @@ function getOscillators() {
}
export function send(bits, startSeconds) {
const oscillators = getOscillators();
const sentBits = [];
getChannels().forEach((channel, i) => {
// send missing bits as zero
const isHigh = bits[i] ?? 0;
callFn(ON_SEND, isHigh);
sentBits.push(isHigh);
const oscillator = oscillators[i];
// already at correct frequency
if(oscillator.on === isHigh) return;
@@ -77,6 +85,7 @@ export function send(bits, startSeconds) {
const hz = channel[isHigh ? 1 : 0];
oscillator.frequency.setValueAtTime(hz, startSeconds);
});
dispatcher.emit('send', {bits: sentBits, startSeconds});
}
const stopTimeout = () => {
if(stopOscillatorsTimeoutId) {
@@ -109,7 +118,6 @@ export function stop() {
}
)
oscillators.length = 0;
callFn(ON_STOP);
dispatcher.emit('end');
stopTimeout();
}
const callFn = (fn, ...args) => typeof fn === 'function' ? fn(...args) : 0;