Newer
Older
DH_Apicture / src / views / voice / lamejs / worker-example / worker.js
@zhangqy zhangqy on 29 Nov 2 KB first commit
  1. (function () {
  2. 'use strict';
  3.  
  4. console.log('MP3 conversion worker started.');
  5. importScripts('../lame.min.js');
  6.  
  7. var mp3Encoder, maxSamples = 1152,
  8. wav, samplesLeft, config, dataBuffer, samplesRight;
  9. var clearBuffer = function () {
  10. dataBuffer = [];
  11. };
  12.  
  13. var appendToBuffer = function (mp3Buf) {
  14. dataBuffer.push(new Int8Array(mp3Buf));
  15. };
  16.  
  17.  
  18. var init = function (prefConfig) {
  19. config = prefConfig || {};
  20. clearBuffer();
  21. };
  22.  
  23. var encode = function (arrayBuffer) {
  24. wav = lamejs.WavHeader.readHeader(new DataView(arrayBuffer));
  25. console.log('wave:', wav);
  26. if (!wav) {
  27. self.postMessage({cmd: 'error', msg: 'Specified file is not a Wave file'});
  28. return;
  29. }
  30.  
  31. var dataView = new Int16Array(arrayBuffer, wav.dataOffset, wav.dataLen / 2);
  32. samplesLeft = wav.channels === 1 ? dataView : new Int16Array(wav.dataLen / (2 * wav.channels));
  33. samplesRight = wav.channels === 2 ? new Int16Array(wav.dataLen / (2 * wav.channels)) : undefined;
  34. if (wav.channels > 1) {
  35. for (var i = 0; i < samplesLeft.length; i++) {
  36. samplesLeft[i] = dataView[i * 2];
  37. samplesRight[i] = dataView[i * 2 + 1];
  38. }
  39. }
  40.  
  41. mp3Encoder = new lamejs.Mp3Encoder(wav.channels, wav.sampleRate, config.bitRate || 96);
  42.  
  43. var remaining = samplesLeft.length;
  44. for (var i = 0; remaining >= maxSamples; i += maxSamples) {
  45. var left = samplesLeft.subarray(i, i + maxSamples);
  46. var right;
  47. if (samplesRight) {
  48. right = samplesRight.subarray(i, i + maxSamples);
  49. }
  50. var mp3buf = mp3Encoder.encodeBuffer(left, right);
  51. appendToBuffer(mp3buf);
  52. remaining -= maxSamples;
  53. self.postMessage({
  54. cmd: 'progress',
  55. progress: (1 - remaining / samplesLeft.length)
  56. });
  57. }
  58. };
  59.  
  60. var finish = function () {
  61. if (!wav) {
  62. return;
  63. }
  64. var mp3buf = mp3Encoder.flush();
  65. appendToBuffer(mp3buf);
  66. self.postMessage({
  67. cmd: 'end',
  68. buf: dataBuffer
  69. });
  70. console.log('done encoding');
  71. clearBuffer(); //free up memory
  72. };
  73.  
  74. self.onmessage = function (e) {
  75. switch (e.data.cmd) {
  76. case 'init':
  77. init(e.data.config);
  78. break;
  79.  
  80. case 'encode':
  81. encode(e.data.rawInput);
  82. break;
  83.  
  84. case 'finish':
  85. finish();
  86. break;
  87. }
  88. };
  89.  
  90. })();