micProcessor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // micProcessor.js
  2. class MicProcessor extends AudioWorkletProcessor
  3. {
  4. constructor()
  5. {
  6. super();
  7. // global variables for testing
  8. var sampleRate = globalThis.sampleRate;
  9. var currentFrame = globalThis.currentFrame;
  10. var currentTime = globalThis.currentTime;
  11. var currentRenderQuantum = globalThis.currentRenderQuantum;
  12. this.SampleRate = sampleRate;
  13. this.TargetSamples = Math.floor(this.SampleRate * 0.1); // 100ms
  14. this.Buffer = new Float32Array(this.TargetSamples);
  15. this.BufferIndex = 0;
  16. this.port.onmessage = (event) =>
  17. {
  18. var data = event.data;
  19. if (typeof data === 'number')
  20. {
  21. //this.port.postMessage(data); // echo back test
  22. }
  23. if (data instanceof Uint8Array)
  24. {
  25. }
  26. };
  27. }
  28. process(inputs, outputs, parameters)
  29. {
  30. var inChannel0 = inputs[0][0];
  31. if (!inChannel0) return true;
  32. let srcIndex = 0;
  33. var srcLen = inChannel0.length;
  34. while (srcIndex < srcLen)
  35. {
  36. var remaining = this.TargetSamples - this.BufferIndex;
  37. var copyCount = Math.min(remaining, srcLen - srcIndex);
  38. this.Buffer.set(
  39. inChannel0.subarray(srcIndex, srcIndex + copyCount),
  40. this.BufferIndex);
  41. this.BufferIndex += copyCount;
  42. srcIndex += copyCount;
  43. if (this.BufferIndex >= this.TargetSamples)
  44. {
  45. this.SendBuffer();
  46. this.BufferIndex = 0;
  47. }
  48. }
  49. return true;
  50. }
  51. SendBuffer()
  52. {
  53. // convert to 16-6bit PCM
  54. var int16 = new Int16Array(this.TargetSamples);
  55. for (var i = 0; i < this.TargetSamples; i++)
  56. {
  57. int16[i] = this.Buffer[i] * 32767;
  58. }
  59. var byteArray = new Uint8Array(int16.buffer);
  60. this.port.postMessage(byteArray, [byteArray.buffer]);
  61. }
  62. }
  63. registerProcessor('mic-processor', MicProcessor);