Newer
Older
DH_Apicture / src / views / voice / lamejs / worker-example / index.js
@zhangqy zhangqy on 29 Nov 2 KB first commit
  1. (function (exports) {
  2. 'use strict';
  3.  
  4. var MP3Converter = function (config) {
  5. config = config || {};
  6. var busy = false;
  7. var mp3Worker = new Worker('worker.js');
  8.  
  9. this.isBusy = function () {
  10. return busy
  11. };
  12.  
  13. this.convert = function (blob) {
  14. var conversionId = 'conversion_' + Date.now(),
  15. tag = conversionId + ":"
  16. ;
  17. var opts = [];
  18. for(var i=1; i < arguments.length;i++){
  19. opts.push(arguments[i]);
  20. }
  21. console.log(tag, 'Starting conversion');
  22. var preferredConfig = {}, onSuccess, onProgress, onError;
  23. if (typeof opts[0] == 'object') {
  24. preferredConfig = opts.shift();
  25. }
  26.  
  27.  
  28. onSuccess = opts.shift();
  29. onProgress = opts.shift();
  30. onError = opts.shift();
  31.  
  32. if (busy) {
  33. throw ("Another conversion is in progress");
  34. }
  35.  
  36. var initialSize = blob.size,
  37. fileReader = new FileReader(),
  38. startTime = Date.now();
  39.  
  40. fileReader.onload = function (e) {
  41. console.log(tag, "Passed to BG process");
  42. mp3Worker.postMessage({
  43. cmd: 'init',
  44. config: preferredConfig
  45. });
  46. mp3Worker.postMessage({cmd: 'encode', rawInput: e.target.result});
  47. mp3Worker.postMessage({cmd: 'finish'});
  48.  
  49. mp3Worker.onmessage = function (e) {
  50. if (e.data.cmd == 'end') {
  51. console.log(tag, "Done converting to Mp3");
  52. var mp3Blob = new Blob(e.data.buf, {type: 'audio/mp3'});
  53. console.log(tag, "Conversion completed in: " + ((Date.now() - startTime) / 1000) + 's');
  54. var finalSize = mp3Blob.size;
  55. console.log(tag +
  56. "Initial size: = " + initialSize + ", " +
  57. "Final size = " + finalSize
  58. + ", Reduction: " + Number((100 * (initialSize - finalSize) / initialSize)).toPrecision(4) + "%");
  59.  
  60. busy = false;
  61.  
  62. if(onProgress && typeof onProgress=='function'){
  63. onProgress(1);
  64. }
  65.  
  66. if (onSuccess && typeof onSuccess === 'function') {
  67. onSuccess(mp3Blob);
  68. }
  69. } else if(e.data.cmd == 'progress'){
  70. //post progress
  71. if(onProgress && typeof onProgress=='function'){
  72. onProgress(e.data.progress);
  73. }
  74. } else if(e.data.cmd == 'error'){
  75.  
  76. }
  77. };
  78. };
  79. busy = true;
  80. fileReader.readAsArrayBuffer(blob);
  81. }
  82. };
  83.  
  84. exports.MP3Converter = MP3Converter;
  85. })(window);