vail/static/scripts/outputs.mjs

560 lines
12 KiB
JavaScript
Raw Normal View History

2023-01-16 17:29:40 -07:00
import {AudioSource, AudioContextTime} from "./audio.mjs"
2022-05-15 10:46:51 -06:00
const HIGH_FREQ = 555
const LOW_FREQ = 444
/**
* A duration.
*
* Because JavaScript has multiple confliction notions of duration,
* everything in vail uses this.
*
* @typedef {number} Duration
*/
/**
* An epoch time, as returned by Date.now().
*
* @typedef {number} Date
*/
const Millisecond = 1
const Second = 1000 * Millisecond
/** The amount of time it should take an oscillator to ramp to and from zero gain
*
* @constant {Duration}
*/
const OscillatorRampDuration = 5*Millisecond
2023-01-16 17:29:40 -07:00
class Oscillator extends AudioSource {
/**
* Create a new oscillator, and encase it in a Gain for control.
*
2023-01-16 17:29:40 -07:00
* @param {AudioContext} context Audio context
* @param {number} frequency Oscillator frequency (Hz)
2023-01-16 17:29:40 -07:00
* @param {number} maxGain Maximum gain (volume) of this oscillator (0.0 - 1.0)
* @param {string} type Oscillator type
*/
2023-01-16 17:29:40 -07:00
constructor(context, frequency, maxGain = 0.5, type = "sine") {
super(context)
this.maxGain = maxGain
// Start quiet
this.masterGain.gain.value = 0
this.osc = new OscillatorNode(this.context)
this.osc.type = type
this.osc.connect(this.masterGain)
this.setFrequency(frequency)
this.osc.start()
}
2023-01-16 17:29:40 -07:00
/**
* Set oscillator frequency
*
* @param {Number} frequency New frequency (Hz)
*/
setFrequency(frequency) {
this.osc.frequency.value = frequency
}
/**
* Set oscillator frequency to a MIDI note number
*
* This uses an equal temperament.
*
* @param {Number} note MIDI note number
*/
setMIDINote(note) {
let frequency = 8.18 // MIDI note 0
for (let i = 0; i < note; i++) {
frequency *= 1.0594630943592953 // equal temperament half step
}
this.setFrequency(frequency)
}
/**
2023-01-16 17:29:40 -07:00
* Set gain to some value at a given time.
*
* @param {number} target Target gain
* @param {Date} when Time this should start
* @param {Duration} timeConstant Duration of ramp to target gain
*/
async setTargetAtTime(target, when, timeConstant=OscillatorRampDuration) {
2023-01-16 17:29:40 -07:00
await this.context.resume()
this.masterGain.gain.setTargetAtTime(
target,
2023-01-16 17:29:40 -07:00
AudioContextTime(this.context, when),
timeConstant/Second,
)
}
2023-01-16 17:29:40 -07:00
/**
* Make sound at a given time.
*
* @param {Number} when When to start making noise
* @param {Number} timeConstant How long to ramp up
* @returns {Promise}
*/
SoundAt(when=0, timeConstant=OscillatorRampDuration) {
2023-01-16 17:29:40 -07:00
return this.setTargetAtTime(this.maxGain, when, timeConstant)
}
2023-01-16 17:29:40 -07:00
/**
* Shut up at a given time.
*
* @param {Number} when When to stop making noise
* @param {Number} timeConstant How long to ramp down
* @returns {Promise}
*/
HushAt(when=0, timeConstant=OscillatorRampDuration) {
return this.setTargetAtTime(0, when, timeConstant)
}
}
/**
* A digital sample, loaded from a URL.
*/
2023-01-16 17:29:40 -07:00
class Sample extends AudioSource {
/**
2023-01-16 17:29:40 -07:00
* @param {AudioContext} context
* @param {string} url URL to resource
*/
2023-01-16 17:29:40 -07:00
constructor(context, url) {
super(context)
this.resume = this.load(url)
}
async load(url) {
let resp = await fetch(url)
let buf = await resp.arrayBuffer()
2023-01-16 17:29:40 -07:00
this.data = await this.context.decodeAudioData(buf)
}
/**
* Play the sample
*
* @param {Date} when When to begin playback
*/
async PlayAt(when) {
2023-01-16 17:29:40 -07:00
await this.context.resume()
await this.resume
2023-01-16 17:29:40 -07:00
let bs = new AudioBufferSourceNode(this.context)
bs.buffer = this.data
2023-01-16 17:29:40 -07:00
bs.connect(this.masterGain)
bs.start(AudioContextTime(this.context, when))
}
}
/**
* A (mostly) virtual class defining a buzzer.
*/
2023-01-16 17:29:40 -07:00
class Buzzer extends AudioSource {
/**
* @param {AudioContext} context
*/
constructor(context) {
super(context)
2022-06-06 10:55:11 -06:00
this.connected = true
}
/**
* Signal an error
*/
Error() {
console.log("Error")
}
/**
* Begin buzzing at time
*
* @param {boolean} tx Transmit or receive tone
* @param {number} when Time to begin, in ms (0=now)
*/
2022-05-22 21:37:36 -06:00
async Buzz(tx, when=0) {
console.log("Buzz", tx, when)
}
/**
* End buzzing at time
*
* @param {boolean} tx Transmit or receive tone
* @param {number} when Time to end, in ms (0=now)
*/
2022-05-22 21:37:36 -06:00
async Silence(tx, when=0) {
console.log("Silence", tx, when)
}
/**
* Buzz for a duration at time
*
* @param {boolean} tx Transmit or receive tone
* @param {number} when Time to begin, in ms (0=now)
* @param {number} duration Duration of buzz (ms)
*/
BuzzDuration(tx, when, duration) {
this.Buzz(tx, when)
this.Silence(tx, when + duration)
}
2022-06-06 10:55:11 -06:00
/**
* Set the "connectedness" indicator.
*
* @param {boolean} connected True if connected
*/
SetConnected(connected) {
this.connected = connected
}
}
class AudioBuzzer extends Buzzer {
2023-01-16 17:29:40 -07:00
/**
* A buzzer that make noise
*
* @param {AudioContext} context
* @param {Number} errorFreq Error tone frequency (hz)
*/
constructor(context, errorFreq=30) {
super(context)
2023-01-16 17:29:40 -07:00
this.errorTone = new Oscillator(this.context, errorFreq, 0.1, "square")
this.errorTone.connect(this.masterGain)
}
Error() {
let now = Date.now()
2023-01-16 17:29:40 -07:00
this.errorTone.SoundAt(now)
this.errorTone.HushAt(now + 200*Millisecond)
}
}
2023-01-16 17:29:40 -07:00
/**
* Buzzers keep two oscillators: one high and one low.
* They generate a continuous waveform,
* and we change the gain to turn the pitches off and on.
*
* This also implements a very quick ramp-up and ramp-down in gain,
* in order to avoid "pops" (square wave overtones)
* that happen with instant changes in gain.
*/
class ToneBuzzer extends AudioBuzzer {
2023-01-16 17:29:40 -07:00
constructor(context, {txGain=0.5, highFreq=HIGH_FREQ, lowFreq=LOW_FREQ} = {}) {
super(context)
2023-01-16 17:29:40 -07:00
this.rxOsc = new Oscillator(this.context, lowFreq, txGain)
this.txOsc = new Oscillator(this.context, highFreq, txGain)
2023-01-16 17:29:40 -07:00
this.rxOsc.connect(this.masterGain)
this.txOsc.connect(this.masterGain)
2022-05-22 21:37:36 -06:00
// Keep the speaker going always. This keeps the browser from "swapping out" our audio context.
if (false) {
2023-01-16 17:29:40 -07:00
this.bgOsc = new Oscillator(this.context, 1, 0.001)
this.bgOsc.SoundAt()
}
}
2023-01-16 17:29:40 -07:00
/**
* Set MIDI note for tx/rx tone
*
* @param {Boolean} tx True to set transmit note
* @param {Number} note MIDI note to send
*/
SetMIDINote(tx, note) {
if (tx) {
this.txOsc.setMIDINote(note)
} else {
this.rxOsc.setMIDINote(note)
}
}
/**
* Begin buzzing at time
*
* @param {boolean} tx Transmit or receive tone
* @param {number} when Time to begin, in ms (0=now)
*/
2022-05-22 21:37:36 -06:00
async Buzz(tx, when = null) {
let osc = tx?this.txOsc:this.rxOsc
osc.SoundAt(when)
}
/**
* End buzzing at time
*
* @param {boolean} tx Transmit or receive tone
* @param {number} when Time to end, in ms (0=now)
*/
2022-05-22 21:37:36 -06:00
async Silence(tx, when = null) {
let osc = tx?this.txOsc:this.rxOsc
osc.HushAt(when)
}
}
class TelegraphBuzzer extends AudioBuzzer{
2023-01-16 17:29:40 -07:00
/**
*
* @param {AudioContext} context
*/
constructor(context) {
super(context)
this.hum = new Oscillator(this.context, 140, 0.005, "sawtooth")
2023-01-16 17:29:40 -07:00
this.closeSample = new Sample(this.context, "../assets/telegraph-a.mp3")
this.openSample = new Sample(this.context, "../assets/telegraph-b.mp3")
2023-01-16 17:29:40 -07:00
this.hum.connect(this.masterGain)
this.closeSample.connect(this.masterGain)
this.openSample.connect(this.masterGain)
}
2022-05-22 21:37:36 -06:00
async Buzz(tx, when=0) {
if (tx) {
this.hum.SoundAt(when)
} else {
this.closeSample.PlayAt(when)
}
}
2022-05-22 21:37:36 -06:00
async Silence(tx ,when=0) {
if (tx) {
this.hum.HushAt(when)
} else {
this.openSample.PlayAt(when)
}
}
}
2022-05-22 21:37:36 -06:00
class LampBuzzer extends Buzzer {
2023-01-16 17:29:40 -07:00
/**
*
* @param {AudioContext} context
*/
constructor(context) {
super(context)
2022-05-22 21:37:36 -06:00
this.elements = document.querySelectorAll(".recv-lamp")
}
2022-05-22 21:37:36 -06:00
async Buzz(tx, when=0) {
if (tx) return
2022-05-14 18:51:05 -06:00
let ms = when?when - Date.now():0
setTimeout(
() =>{
2022-05-22 21:37:36 -06:00
for (let e of this.elements) {
e.classList.add("rx")
}
2022-05-14 18:51:05 -06:00
},
ms,
)
}
2022-05-22 21:37:36 -06:00
async Silence(tx, when=0) {
if (tx) return
2022-05-14 18:51:05 -06:00
let ms = when?when - Date.now():0
2022-05-22 21:37:36 -06:00
setTimeout(
() => {
for (let e of this.elements) {
e.classList.remove("rx")
}
},
ms,
)
}
2022-06-06 10:55:11 -06:00
SetConnected(connected) {
for (let e of this.elements) {
if (connected) {
e.classList.add("connected")
} else {
e.classList.remove("connected")
}
}
}
2022-05-22 21:37:36 -06:00
}
class MIDIBuzzer extends Buzzer {
2023-01-16 17:29:40 -07:00
/**
*
* @param {AudioContext} context
*/
constructor(context) {
super(context)
this.SetMIDINote(69) // A4; 440Hz
2022-05-22 21:37:36 -06:00
this.midiAccess = {outputs: []} // stub while we wait for async stuff
if (navigator.requestMIDIAccess) {
this.midiInit()
}
}
async midiInit(access) {
this.outputs = new Set()
this.midiAccess = await navigator.requestMIDIAccess()
this.midiAccess.addEventListener("statechange", e => this.midiStateChange(e))
this.midiStateChange()
}
midiStateChange(event) {
let newOutputs = new Set()
for (let output of this.midiAccess.outputs.values()) {
if ((output.state != "connected") || (output.name.includes("Through"))) {
continue
}
newOutputs.add(output)
}
this.outputs = newOutputs
}
sendAt(when, message) {
let ms = when?when - Date.now():0
setTimeout(
() => {
2022-06-26 12:22:57 -06:00
for (let output of (this.outputs || [])) {
2022-05-22 21:37:36 -06:00
output.send(message)
}
},
ms,
)
}
async Buzz(tx, when=0) {
if (tx) {
return
}
this.sendAt(when, [0x90, this.note, 0x7f])
}
async Silence(tx, when=0) {
if (tx) {
return
}
this.sendAt(when, [0x80, this.note, 0x7f])
}
2023-01-16 17:29:40 -07:00
/**
* Set MIDI note for tx/rx tone
*
* @param {Boolean} tx True to set transmit note
* @param {Number} note MIDI note to send
*/
SetMIDINote(tx, note) {
2022-05-22 21:37:36 -06:00
if (tx) {
return
}
this.note = note
}
}
2023-01-16 17:29:40 -07:00
class Collection extends AudioSource {
/**
*
* @param {AudioContext} context Audio Context
*/
constructor(context) {
super(context)
this.tone = new ToneBuzzer(this.context)
this.telegraph = new TelegraphBuzzer(this.context)
this.lamp = new LampBuzzer(this.context)
this.midi = new MIDIBuzzer(this.context)
2022-05-22 21:37:36 -06:00
this.collection = new Set([this.tone, this.lamp, this.midi])
2023-01-16 17:29:40 -07:00
this.tone.connect(this.masterGain)
this.telegraph.connect(this.masterGain)
this.lamp.connect(this.masterGain)
this.midi.connect(this.masterGain)
2022-05-22 21:37:36 -06:00
}
/**
* Set the audio output type.
*
* @param {string} audioType "telegraph" for telegraph mode, otherwise tone mode
*/
SetAudioType(audioType) {
2023-01-16 17:29:40 -07:00
this.Panic()
2022-05-22 21:37:36 -06:00
this.collection.delete(this.telegraph)
this.collection.delete(this.tone)
if (audioType == "telegraph") {
this.collection.add(this.telegraph)
} else {
this.collection.add(this.tone)
}
}
/**
* Buzz all outputs.
*
* @param tx True if transmitting
*/
Buzz(tx=False) {
for (let b of this.collection) {
b.Buzz(tx)
}
}
/**
2023-01-16 17:29:40 -07:00
* Silence all outputs in a single direction.
2022-05-22 21:37:36 -06:00
*
* @param tx True if transmitting
*/
2022-06-06 10:55:11 -06:00
Silence(tx=false) {
2022-05-22 21:37:36 -06:00
for (let b of this.collection) {
b.Silence(tx)
}
}
2023-01-16 17:29:40 -07:00
/**
* Silence all outputs.
*/
Panic() {
this.Silence(true)
this.Silence(false)
}
/**
*
* @param {Boolean} tx True to set transmit tone
* @param {Number} note MIDI note to set
*/
SetMIDINote(tx, note) {
for (let b of this.collection) {
if (b.SetMIDINote) {
b.SetMIDINote(tx, note)
}
}
}
2022-05-22 21:37:36 -06:00
/**
* Buzz for a certain duration at a certain time
*
* @param tx True if transmitting
* @param when Time to begin
* @param duration How long to buzz
*/
BuzzDuration(tx, when, duration) {
for (let b of this.collection) {
b.BuzzDuration(tx, when, duration)
}
}
2022-06-06 10:55:11 -06:00
/**
* Update the "connected" status display.
*
* For example, turn the receive light to black if the repeater is not connected.
*
* @param {boolean} connected True if we are "connected"
*/
SetConnected(connected) {
for (let b of this.collection) {
b.SetConnected(connected)
}
}
}
2023-01-16 17:29:40 -07:00
export {Collection}