utils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Adapted from https://www.npmjs.com/package/audiobuffer-to-wav
  2. export function encodeWAV(samples) {
  3. let offset = 44;
  4. const buffer = new ArrayBuffer(offset + samples.length * 4);
  5. const view = new DataView(buffer);
  6. const sampleRate = 16000;
  7. /* RIFF identifier */
  8. writeString(view, 0, 'RIFF')
  9. /* RIFF chunk length */
  10. view.setUint32(4, 36 + samples.length * 4, true)
  11. /* RIFF type */
  12. writeString(view, 8, 'WAVE')
  13. /* format chunk identifier */
  14. writeString(view, 12, 'fmt ')
  15. /* format chunk length */
  16. view.setUint32(16, 16, true)
  17. /* sample format (raw) */
  18. view.setUint16(20, 3, true)
  19. /* channel count */
  20. view.setUint16(22, 1, true)
  21. /* sample rate */
  22. view.setUint32(24, sampleRate, true)
  23. /* byte rate (sample rate * block align) */
  24. view.setUint32(28, sampleRate * 4, true)
  25. /* block align (channel count * bytes per sample) */
  26. view.setUint16(32, 4, true)
  27. /* bits per sample */
  28. view.setUint16(34, 32, true)
  29. /* data chunk identifier */
  30. writeString(view, 36, 'data')
  31. /* data chunk length */
  32. view.setUint32(40, samples.length * 4, true)
  33. for (let i = 0; i < samples.length; ++i, offset += 4) {
  34. view.setFloat32(offset, samples[i], true)
  35. }
  36. return buffer
  37. }
  38. function writeString(view, offset, string) {
  39. for (let i = 0; i < string.length; ++i) {
  40. view.setUint8(offset + i, string.charCodeAt(i))
  41. }
  42. }