rec.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /* AudioWorkletProcesser must be initialized as modules (i.e. seperate files)
  2. * Ref : https://developer.mozilla.org/en-US/docs/Web/API/AudioWorkletProcessor
  3. */
  4. class TimedRecorder extends AudioWorkletProcessor {
  5. constructor(options) {
  6. super()
  7. this.max_length = 0
  8. this.recbuffer = new Float32Array()
  9. this.recording = false
  10. this.buf_index = 0
  11. this.port.onmessage = (event) => {
  12. switch (event.data.message) {
  13. case 'start':
  14. this.max_length = event.data.duration * 8000
  15. this.recbuffer = new Float32Array(this.max_length)
  16. this.buf_index = 0
  17. this.recording = true
  18. this.port.postMessage({ message: '[rec.js] Recording started' })
  19. break
  20. }
  21. }
  22. }
  23. process(inputs) {
  24. // Only take care of channel 0 (Left)
  25. if (this.recording) {
  26. let channelL = inputs[0][0]
  27. this.port.postMessage({
  28. message: 'bufferhealth',
  29. health: this.buf_index / this.max_length,
  30. recording: this.recbuffer,
  31. })
  32. if (this.buf_index + channelL.length > this.max_length) {
  33. this.port.postMessage({ message: '[rec.js] Recording finished' })
  34. this.recording = false
  35. this.buf_index = 0
  36. this.port.postMessage({
  37. message: 'finished',
  38. recording: this.recbuffer,
  39. })
  40. } else {
  41. this.recbuffer.set(channelL, this.buf_index)
  42. this.buf_index += channelL.length
  43. }
  44. }
  45. return true
  46. }
  47. }
  48. registerProcessor('timed-recorder', TimedRecorder)