Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- const WebSocket = require('ws');
- var express = require('express');
- var watson = require('watson-developer-cloud');
- var vcapServices = require('vcap_services');
- var extend = (extend = require('util')._extend);
- var fs = require('fs');
- var ttsConfig = extend(
- {
- version: 'v1',
- url: 'https://stream.watsonplatform.net/text-to-speech/api',
- username: 'myusernamehere',
- password: "mypasswordhere"
- },
- vcapServices.getCredentials('text_to_speech')
- );
- var ttsAuthService = watson.authorization(ttsConfig);
- var websocket;
- ttsAuthService.getToken({ url: ttsConfig.url }, function(err, token) {
- if (err) {
- console.log('Error retrieving token: ', err);
- return;
- }
- var voice = 'en-US_AllisonVoice';
- var wsURI = 'wss://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=' +
- voice + '&watson-token=' + token;
- websocket = new WebSocket(wsURI);
- websocket.onopen = function(evt) { onOpen(evt) };
- websocket.onclose = function(evt) { onClose(evt) };
- websocket.onmessage = function(evt) { onMessage(evt) };
- websocket.onerror = function(evt) { onError(evt) };
- });
- function onOpen(evt) {
- var message = {
- text: 'Hello world',
- accept: 'audio/wav',
- timings: ['words']
- };
- websocket.send(JSON.stringify(message));
- }
- var messages;
- var audioStream = null;
- function onMessage(evt) {
- if (typeof evt.data === 'string') {
- messages += evt.data;
- } else {
- if(audioStream == null){
- audioStream = evt.data;
- }else{
- audioStream += evt.data;
- }
- }
- }
- function onClose(evt) {
- console.log(messages);
- var wstream = fs.createWriteStream('test.wav');
- wstream.write((audioStream));
- wstream.end();
- }
- function onError(evt) {
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement