Files
bruitiste/src/domain/audio/effects/FoldCrushEffect.ts

81 lines
2.3 KiB
TypeScript

import type { Effect } from './Effect.interface'
export class FoldCrushEffect implements Effect {
readonly id = 'foldcrush'
private inputNode: GainNode
private outputNode: GainNode
private processorNode: AudioWorkletNode | null = null
private wetNode: GainNode
private dryNode: GainNode
constructor(audioContext: AudioContext) {
this.inputNode = audioContext.createGain()
this.outputNode = audioContext.createGain()
this.wetNode = audioContext.createGain()
this.dryNode = audioContext.createGain()
this.wetNode.gain.value = 0
this.dryNode.gain.value = 1
this.inputNode.connect(this.dryNode)
this.dryNode.connect(this.outputNode)
}
async initialize(audioContext: AudioContext): Promise<void> {
try {
this.processorNode = new AudioWorkletNode(audioContext, 'fold-crush-processor')
this.inputNode.connect(this.processorNode)
this.processorNode.connect(this.wetNode)
this.wetNode.connect(this.outputNode)
} catch (error) {
console.error('Failed to initialize FoldCrushEffect worklet:', error)
}
}
getInputNode(): AudioNode {
return this.inputNode
}
getOutputNode(): AudioNode {
return this.outputNode
}
setBypass(bypass: boolean): void {
if (bypass) {
this.wetNode.gain.value = 0
this.dryNode.gain.value = 1
} else {
this.wetNode.gain.value = 1
this.dryNode.gain.value = 0
}
}
updateParams(values: Record<string, number | string>): void {
if (!this.processorNode) return
if (values.clipMode !== undefined) {
this.processorNode.port.postMessage({ type: 'clipMode', value: values.clipMode })
}
if (values.wavefolderDrive !== undefined) {
this.processorNode.port.postMessage({ type: 'drive', value: values.wavefolderDrive })
}
if (values.bitcrushDepth !== undefined) {
this.processorNode.port.postMessage({ type: 'bitDepth', value: values.bitcrushDepth })
}
if (values.bitcrushRate !== undefined) {
this.processorNode.port.postMessage({ type: 'crushAmount', value: values.bitcrushRate })
}
}
dispose(): void {
if (this.processorNode) {
this.processorNode.disconnect()
}
this.wetNode.disconnect()
this.dryNode.disconnect()
this.inputNode.disconnect()
this.outputNode.disconnect()
}
}