utils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import lamejs from 'lamejs'
  2. import MPEGMode from 'lamejs/src/js/MPEGMode'
  3. import Lame from 'lamejs/src/js/Lame'
  4. import BitStream from 'lamejs/src/js/BitStream'
  5. if (globalThis) {
  6. (globalThis as any).MPEGMode = MPEGMode
  7. ;(globalThis as any).Lame = Lame
  8. ;(globalThis as any).BitStream = BitStream
  9. }
  10. export const convertToMp3 = (recorder: any) => {
  11. const wav = lamejs.WavHeader.readHeader(recorder.getWAV())
  12. const { channels, sampleRate } = wav
  13. const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128)
  14. const result = recorder.getChannelData()
  15. const buffer = []
  16. const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2)
  17. const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2)
  18. const remaining = leftData.length + (rightData ? rightData.length : 0)
  19. const maxSamples = 1152
  20. for (let i = 0; i < remaining; i += maxSamples) {
  21. const left = leftData.subarray(i, i + maxSamples)
  22. let right = null
  23. let mp3buf = null
  24. if (channels === 2) {
  25. right = rightData.subarray(i, i + maxSamples)
  26. mp3buf = mp3enc.encodeBuffer(left, right)
  27. }
  28. else {
  29. mp3buf = mp3enc.encodeBuffer(left)
  30. }
  31. if (mp3buf.length > 0)
  32. buffer.push(mp3buf)
  33. }
  34. const enc = mp3enc.flush()
  35. if (enc.length > 0)
  36. buffer.push(enc)
  37. return new Blob(buffer, { type: 'audio/mp3' })
  38. }