|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const fs = require('fs'); |
| 4 | +const TextToSpeechV1 = require('watson-developer-cloud/text-to-speech/v1'); |
| 5 | + |
| 6 | +const textToSpeech = new TextToSpeechV1({ |
| 7 | + // if left unspecified here, the SDK will fall back to the TEXT_TO_SPEECH_USERNAME and TEXT_TO_SPEECH_PASSWORD |
| 8 | + // environment properties, and then IBM Cloud's VCAP_SERVICES environment property |
| 9 | + // username: 'INSERT YOUR USERNAME FOR THE SERVICE HERE', |
| 10 | + // password: 'INSERT YOUR PASSWORD FOR THE SERVICE HERE' |
| 11 | +}); |
| 12 | + |
| 13 | +// specify the text to synthesize |
| 14 | +const params = { |
| 15 | + text: 'Hello, world.', |
| 16 | + accept: 'audio/ogg;codecs=opus', |
| 17 | +}; |
| 18 | + |
| 19 | +// synthesizeUsingWebSocket returns a Readable Stream that can be piped or listened to |
| 20 | +const synthesizeStream = textToSpeech.synthesizeUsingWebSocket(params); |
| 21 | + |
| 22 | +// the output of the stream can be piped to any writable stream, like an audio file |
| 23 | +synthesizeStream.pipe(fs.createWriteStream('./speech.ogg')); |
| 24 | + |
| 25 | +// if the stream is not being piped anywhere and is only being listened to, the stream needs |
| 26 | +// to be explicitly set to flowing mode: |
| 27 | + |
| 28 | +// synthesizeStream.resume(); |
| 29 | + |
| 30 | +// the 'message' event is emitted when data is processed and returned from the service |
| 31 | +// the 'message' parameter is the entire response frame of information returned from the |
| 32 | +// service. it is mainly useful for debugging |
| 33 | +// the 'data' parameter is the data payload contained within the message. it is typically |
| 34 | +// binary audio data, but if the text includes SSML marks or the request includes the |
| 35 | +// 'timings' parameter, 'data' could be a string containing marks or timing information |
| 36 | +synthesizeStream.on('message', (message, data) => { |
| 37 | + console.log(data); |
| 38 | +}); |
| 39 | + |
| 40 | +// the 'error' event is emitted if there is an error during the connection |
| 41 | +// 'err' is the Error object describing the error |
| 42 | +synthesizeStream.on('error', err => { |
| 43 | + console.log(err); |
| 44 | +}); |
| 45 | + |
| 46 | +// the 'close' event is emitted once, when the connection is terminated by the service |
| 47 | +// the 'code' parameter is the status code. 1000 is the code for a normal termination |
| 48 | +// the 'reason' parameter provides a string description of how the connection closed |
| 49 | +synthesizeStream.on('close', (code, reason) => { |
| 50 | + console.log(code); |
| 51 | +}); |
0 commit comments