JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
</head>
<button id="btn">
Start
</button>
<script>
let aa;
window.sab = new SharedArrayBuffer(1024);
document.body.addEventListener('click', async function() {
if (aa) {
return;
}
console.log('initializing audio context');
aa = new AudioContext({sampleRate: 16000});
await aa.resume();
console.log('tasnim, the state:' + aa.state);
await aa.audioWorklet.addModule('white-noise-processor.js');
console.log('added module');
const whiteNoiseNode = new WorkletNode(aa, {
'processorOptions': {
'buf': 4,
'buffer': window.sab
},
}
);
whiteNoiseNode.connect(aa.destination);
console.log('connected node');
window.blah = aa;
});
class WorkletNode extends AudioWorkletNode {
constructor(context, options) {
super(context, 'white-noise-processor', options);
this.port.onmessage = function(event) {
if (event.data['message'] == 'PROCESS') {
console.log('audio processor: ' + event.data['v']);
} else if (event.data['message'] == 'ERROR') {
console.error('ERROR: ' + event.data['v']);
}
}
}
}
</script>
}
</html>
JavaScript
// // white-noise-processor.js
class WhiteNodeProcessor extends AudioWorkletProcessor {
constructor(options) {
super();
try {
this.buf_ = options.processorOptions['buf'];
this.sab_ = options.processorOptions['buffer'];
} catch (err) {
this.port.postMessage({'message': 'ERROR', 'v': err.message + ' ' + err.stack});
}
}
process (inputs, outputs, parameters) {
this.port.postMessage({'message': 'PROCESS', 'v': new Int16Array(this.sab_)[0]});
return true;
}
}
registerProcessor('white-noise-processor', WhiteNodeProcessor);