Skip to content

Commit a9bcb11

Browse files
committed
docs(Text to Speech): Add WebSocket example in README
1 parent 9214b68 commit a9bcb11

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

text-to-speech/README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,44 @@ Voices voices = service.listVoices().execute();
2727
System.out.println(voices);
2828
```
2929

30+
## Usage with WebSockets
31+
The Watson Text to Speech service supports the use of WebSockets as an alternative to the `synthesize()` method, which converts text to speech. Here is an example of using the WebSocket version of the method to get an audio file:
32+
```java
33+
TextToSpeech service = new TextToSpeech();
34+
service.setUsernameAndPassword("<username>", "<password>");
35+
36+
String text = "It's beginning to look a lot like Christmas";
37+
SynthesizeOptions synthesizeOptions = new SynthesizeOptions.Builder()
38+
.text(text)
39+
.accept(SynthesizeOptions.Accept.AUDIO_OGG_CODECS_OPUS)
40+
.build();
41+
42+
// a callback is defined to handle certain events, like an audio transmission or a timing marker
43+
// in this case, we'll build up a byte array of all the received bytes to build the resulting file
44+
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
45+
service.synthesizeUsingWebSocket(synthesizeOptions, new BaseSynthesizeCallback() {
46+
@Override
47+
public void onAudioStream(byte[] bytes) {
48+
// append to our byte array
49+
try {
50+
byteArrayOutputStream.write(bytes);
51+
} catch (IOException e) {
52+
e.printStackTrace();
53+
}
54+
}
55+
});
56+
57+
// quick way to wait for synthesis to complete, since synthesizeUsingWebSocket() runs asynchronously
58+
Thread.sleep(5000);
59+
60+
// create file with audio data
61+
String filename = "synthesize_websocket_test.ogg";
62+
OutputStream fileOutputStream = new FileOutputStream(filename);
63+
byteArrayOutputStream.writeTo(fileOutputStream);
64+
65+
// clean up
66+
byteArrayOutputStream.close();
67+
fileOutputStream.close();
68+
```
69+
3070
[text_to_speech]: https://console.bluemix.net/docs/services/text-to-speech/index.html

0 commit comments

Comments
 (0)