streamProcessor.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // streamProcessor.js
  2. class StreamProcessor extends AudioWorkletProcessor
  3. {
  4. constructor()
  5. {
  6. super();
  7. this.queue = [];
  8. this.port.onmessage = (event) =>
  9. {
  10. var data = event.data;
  11. if (typeof data === 'number')
  12. {
  13. if (data === 2)
  14. {
  15. this.queue = [];
  16. }
  17. }
  18. if (data instanceof Uint8Array)
  19. {
  20. const buffer = new Int16Array(data.buffer, data.byteOffset, data.length / 2);
  21. buffer.offset = 0;
  22. this.queue.push(buffer);
  23. }
  24. };
  25. }
  26. process(inputs, outputs, parameters)
  27. {
  28. const output = outputs[0];
  29. const channelCount = output.length;
  30. const sampleCount = output[0].length;
  31. let written = 0;
  32. while (written < sampleCount && this.queue.length > 0)
  33. {
  34. const buffer = this.queue[0];
  35. const offset = buffer.offset;
  36. const available = buffer.length - offset;
  37. const needed = sampleCount - written;
  38. const copyCount = Math.min(available, needed);
  39. for (let i = 0; i < copyCount; i++)
  40. {
  41. for (let c = 0; c < channelCount; c++)
  42. {
  43. const channel = output[c];
  44. let value = (buffer[offset+i] / 32767);
  45. channel[written+i] = value;
  46. }
  47. }
  48. written += copyCount;
  49. buffer.offset += copyCount;
  50. if (buffer.offset >= buffer.length)
  51. {
  52. this.queue.shift();
  53. this.port.postMessage(1);
  54. }
  55. }
  56. // Fill remaining samples with silence
  57. if (written < sampleCount)
  58. {
  59. for (let c = 0; c < channelCount; c++)
  60. {
  61. const channel = output[c];
  62. for (let i = written; i < sampleCount; i++)
  63. {
  64. let value = 0;
  65. channel[i] = value;
  66. }
  67. }
  68. }
  69. return true;
  70. }
  71. }
  72. registerProcessor("stream-processor", StreamProcessor);