espeakng.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2014-2017 Eitan Isaacson
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, see: <http://www.gnu.org/licenses/>.
  16. */
  17. function eSpeakNG(worker_path, ready_cb) {
  18. this.worker = new Worker(worker_path);
  19. this.ready = false;
  20. this.worker.onmessage = function(e) {
  21. if (e.data !== 'ready') {
  22. return;
  23. }
  24. this.worker.onmessage = null;
  25. this.worker.addEventListener('message', this);
  26. this.ready = true;
  27. if (ready_cb) {
  28. ready_cb();
  29. }
  30. }.bind(this);
  31. }
  32. eSpeakNG.prototype.handleEvent = function (evt) {
  33. var callback = evt.data.callback;
  34. if (callback && this[callback]) {
  35. this[callback].apply(this, evt.data.result);
  36. if (evt.data.done) {
  37. delete this[callback];
  38. }
  39. return;
  40. }
  41. };
  42. function _createAsyncMethod(method) {
  43. return function() {
  44. var lastArg = arguments[arguments.length - 1];
  45. var message = { method: method, args: Array.prototype.slice.call(arguments, 0) };
  46. if (typeof lastArg == 'function') {
  47. var callback = '_' + method + '_' + Math.random().toString().substring(2) +'_cb';
  48. this[callback] = lastArg;
  49. message.args.pop();
  50. message.callback = callback;
  51. }
  52. this.worker.postMessage(message);
  53. };
  54. }
  55. for (var method of [
  56. 'list_voices',
  57. 'get_rate',
  58. 'get_pitch',
  59. 'set_rate',
  60. 'set_pitch',
  61. 'set_voice',
  62. 'synthesize',
  63. 'synthesize_ipa'
  64. ]) {
  65. eSpeakNG.prototype[method] = _createAsyncMethod(method);
  66. }