audio-processor.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // @ts-nocheck
  2. class AudioRecorderProcessor extends AudioWorkletProcessor {
  3. constructor() {
  4. super();
  5. this.isRecording = false;
  6. this.bufferSize = 2400; // 100ms at 24kHz
  7. this.currentBuffer = [];
  8. this.port.onmessage = (event) => {
  9. if (event.data.command === "START_RECORDING") {
  10. this.isRecording = true;
  11. } else if (event.data.command === "STOP_RECORDING") {
  12. this.isRecording = false;
  13. if (this.currentBuffer.length > 0) {
  14. this.sendBuffer();
  15. }
  16. }
  17. };
  18. }
  19. sendBuffer() {
  20. if (this.currentBuffer.length > 0) {
  21. const audioData = new Float32Array(this.currentBuffer);
  22. this.port.postMessage({
  23. eventType: "audio",
  24. audioData: audioData,
  25. });
  26. this.currentBuffer = [];
  27. }
  28. }
  29. process(inputs) {
  30. const input = inputs[0];
  31. if (input.length > 0 && this.isRecording) {
  32. const audioData = input[0];
  33. this.currentBuffer.push(...audioData);
  34. if (this.currentBuffer.length >= this.bufferSize) {
  35. this.sendBuffer();
  36. }
  37. }
  38. return true;
  39. }
  40. }
  41. registerProcessor("audio-recorder-processor", AudioRecorderProcessor);