Advertisement
Guest User

Untitled

a guest
Oct 9th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. 'use strict';
  2. const WebSocket = require('ws');
  3. var express = require('express');
  4. var watson = require('watson-developer-cloud');
  5. var vcapServices = require('vcap_services');
  6. var extend = (extend = require('util')._extend);
  7. var fs = require('fs');
  8.  
  9.  
  10. var ttsConfig = extend(
  11. {
  12. version: 'v1',
  13. url: 'https://stream.watsonplatform.net/text-to-speech/api',
  14. username: 'myusernamehere',
  15. password: "mypasswordhere"
  16. },
  17. vcapServices.getCredentials('text_to_speech')
  18. );
  19.  
  20. var ttsAuthService = watson.authorization(ttsConfig);
  21.  
  22.  
  23. var websocket;
  24. ttsAuthService.getToken({ url: ttsConfig.url }, function(err, token) {
  25. if (err) {
  26. console.log('Error retrieving token: ', err);
  27.  
  28. return;
  29. }
  30.  
  31. var voice = 'en-US_AllisonVoice';
  32. var wsURI = 'wss://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=' +
  33. voice + '&watson-token=' + token;
  34.  
  35.  
  36. websocket = new WebSocket(wsURI);
  37. websocket.onopen = function(evt) { onOpen(evt) };
  38. websocket.onclose = function(evt) { onClose(evt) };
  39. websocket.onmessage = function(evt) { onMessage(evt) };
  40. websocket.onerror = function(evt) { onError(evt) };
  41.  
  42. });
  43.  
  44. function onOpen(evt) {
  45.  
  46. var message = {
  47. text: 'Hello world',
  48. accept: 'audio/wav',
  49. timings: ['words']
  50. };
  51. websocket.send(JSON.stringify(message));
  52. }
  53. var messages;
  54. var audioStream = null;
  55.  
  56. function onMessage(evt) {
  57. if (typeof evt.data === 'string') {
  58. messages += evt.data;
  59. } else {
  60.  
  61. if(audioStream == null){
  62. audioStream = evt.data;
  63. }else{
  64. audioStream += evt.data;
  65. }
  66. }
  67.  
  68. }
  69.  
  70. function onClose(evt) {
  71.  
  72. console.log(messages);
  73. var wstream = fs.createWriteStream('test.wav');
  74. wstream.write((audioStream));
  75. wstream.end();
  76.  
  77. }
  78.  
  79. function onError(evt) {
  80.  
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement