Example 3: Bidirectional streaming. Demonstrates how to use WebSocket-based streaming for real-time text-to-speech. This allows you to send text incrementally and receive audio chunks as they're generated, enabling low-latency conversational experiences.
()
| 192 | /// enabling low-latency conversational experiences. |
| 193 | /// </summary> |
| 194 | static async Task Example3Async() |
| 195 | { |
| 196 | Console.WriteLine("Example 3: Bidirectional streaming..."); |
| 197 | |
| 198 | using var streamingTtsClient = new StreamingTtsClient(_apiKey!); |
| 199 | await streamingTtsClient.ConnectAsync(); |
| 200 | |
| 201 | // Start audio player for raw PCM playback |
| 202 | using var player = StartAudioPlayer(usePcmFormat: true); |
| 203 | await player.StartAsync(); |
| 204 | |
| 205 | // Use silence filler to handle gaps between utterances (like TypeScript's createSilenceFiller) |
| 206 | using var silenceFiller = new SilenceFiller(player.Stdin!); |
| 207 | |
| 208 | // Task 1: Send text input to the TTS service |
| 209 | var sendInputTask = Task.Run(async () => |
| 210 | { |
| 211 | await streamingTtsClient.SendAsync(new { text = "Hello" }); |
| 212 | await streamingTtsClient.SendAsync(new { text = " world." }); |
| 213 | // The whitespace ^ is important, otherwise the model would see |
| 214 | // "Helloworld." and not "Hello world." |
| 215 | await streamingTtsClient.SendFlushAsync(); |
| 216 | |
| 217 | // Simulate a delay before continuing the conversation |
| 218 | Console.WriteLine("Waiting 8 seconds..."); |
| 219 | await Task.Delay(TimeSpan.FromSeconds(VoiceCreationDelaySeconds)); |
| 220 | |
| 221 | await streamingTtsClient.SendAsync(new { text = "Goodbye, world." }); |
| 222 | await streamingTtsClient.SendFlushAsync(); |
| 223 | |
| 224 | await streamingTtsClient.SendCloseAsync(); |
| 225 | }); |
| 226 | |
| 227 | // Task 2: Receive and play audio chunks as they arrive |
| 228 | var handleMessagesTask = Task.Run(async () => |
| 229 | { |
| 230 | Console.WriteLine("Playing audio: Example 3 - Bidirectional streaming"); |
| 231 | await foreach (var chunk in streamingTtsClient.ReceiveAudioChunksAsync()) |
| 232 | { |
| 233 | var audioBytes = Convert.FromBase64String(chunk.Audio); |
| 234 | silenceFiller.WriteAudio(audioBytes); |
| 235 | } |
| 236 | await silenceFiller.EndStreamAsync(); |
| 237 | await player.StopAsync(); |
| 238 | }); |
| 239 | |
| 240 | await Task.WhenAll(sendInputTask, handleMessagesTask); |
| 241 | |
| 242 | Console.WriteLine("Done!"); |
| 243 | } |
| 244 | |
| 245 | /// <summary> |
| 246 | /// Helper method to stream audio chunks from a TTS response to an audio player. |
nothing calls this directly
no test coverage detected