@@ -41,7 +41,7 @@ Follow these steps to create a new console application.
41
41
```
42
42
1. Replace the contents of `Program.cs` with the following code.
43
43
44
- ```csharp
44
+ ```csharp
45
45
using System;
46
46
using System.IO;
47
47
using System.Threading.Tasks;
@@ -64,42 +64,67 @@ Follow these steps to create a new console application.
64
64
// This example requires environment variables named "SPEECH_KEY" and "SPEECH_REGION"
65
65
static string speechKey = Environment.GetEnvironmentVariable("SPEECH_KEY");
66
66
static string speechRegion = Environment.GetEnvironmentVariable("SPEECH_REGION");
67
-
67
+
68
+ // Sentence end symbols for splitting the response into sentences.
69
+ static List<string> sentenceSaperators = new() { ".", "!", "?", ";", "。", "!", "?", ";", "\n" };
70
+
71
+ private static object consoleLock = new();
72
+
68
73
// Prompts Azure OpenAI with a request and synthesizes the response.
69
74
async static Task AskOpenAI(string prompt)
70
75
{
76
+ var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
77
+ // The language of the voice that speaks.
78
+ speechConfig.SpeechSynthesisVoiceName = "en-US-JennyMultilingualNeural";
79
+ var audioOutputConfig = AudioConfig.FromDefaultSpeakerOutput();
80
+ using var speechSynthesizer = new SpeechSynthesizer(speechConfig, audioOutputConfig);
81
+ speechSynthesizer.Synthesizing += (sender, args) =>
82
+ {
83
+ lock (consoleLock)
84
+ {
85
+ Console.ForegroundColor = ConsoleColor.Yellow;
86
+ Console.Write($"[Audio]");
87
+ Console.ResetColor();
88
+ }
89
+ };
90
+
71
91
// Ask Azure OpenAI
72
92
OpenAIClient client = new(new Uri(openAIEndpoint), new AzureKeyCredential(openAIKey));
73
93
var completionsOptions = new CompletionsOptions()
74
94
{
75
95
Prompts = { prompt },
76
96
MaxTokens = 100,
97
+
77
98
};
78
- Response<Completions> completionsResponse = client.GetCompletions(engine, completionsOptions);
79
- string text = completionsResponse.Value.Choices[0].Text.Trim();
80
- Console.WriteLine($"Azure OpenAI response: {text}");
81
-
82
- var speechConfig = SpeechConfig.FromSubscription(speechKey, speechRegion);
83
- // The language of the voice that speaks.
84
- speechConfig.SpeechSynthesisVoiceName = "en-US-JennyMultilingualNeural";
85
- var audioOutputConfig = AudioConfig.FromDefaultSpeakerOutput();
86
-
87
- using (var speechSynthesizer = new SpeechSynthesizer(speechConfig, audioOutputConfig))
99
+ var responseStream = await client.GetCompletionsStreamingAsync(engine, completionsOptions);
100
+ using var streamingCompletions = responseStream.Value;
101
+ StringBuilder gptBuffer = new();
102
+ await foreach (var choice in streamingCompletions.GetChoicesStreaming())
88
103
{
89
- var speechSynthesisResult = await speechSynthesizer.SpeakTextAsync(text).ConfigureAwait(true);
90
-
91
- if (speechSynthesisResult.Reason == ResultReason.SynthesizingAudioCompleted)
104
+ await foreach (var message in choice.GetTextStreaming())
92
105
{
93
- Console.WriteLine($"Speech synthesized to speaker for text: [{text}]");
94
- }
95
- else if (speechSynthesisResult.Reason == ResultReason.Canceled)
96
- {
97
- var cancellationDetails = SpeechSynthesisCancellationDetails.FromResult(speechSynthesisResult);
98
- Console.WriteLine($"Speech synthesis canceled: {cancellationDetails.Reason}");
99
-
100
- if (cancellationDetails.Reason == CancellationReason.Error)
106
+ if (string.IsNullOrEmpty(message))
107
+ {
108
+ continue;
109
+ }
110
+
111
+ lock (consoleLock)
101
112
{
102
- Console.WriteLine($"Error details: {cancellationDetails.ErrorDetails}");
113
+ Console.ForegroundColor = ConsoleColor.DarkBlue;
114
+ Console.Write($"{message}");
115
+ Console.ResetColor();
116
+ }
117
+
118
+ gptBuffer.Append(message);
119
+
120
+ if (sentenceSaperators.Any(message.Contains))
121
+ {
122
+ var sentence = gptBuffer.ToString().Trim();
123
+ if (!string.IsNullOrEmpty(sentence))
124
+ {
125
+ await speechSynthesizer.SpeakTextAsync(sentence).ConfigureAwait(true);
126
+ gptBuffer.Clear();
127
+ }
103
128
}
104
129
}
105
130
}
@@ -164,7 +189,7 @@ Follow these steps to create a new console application.
164
189
}
165
190
}
166
191
}
167
- ```
192
+ ```
168
193
169
194
1 . To increase or decrease the number of tokens returned by Azure OpenAI, change the ` MaxTokens ` property in the ` CompletionsOptions ` class instance. For more information tokens and cost implications, see [ Azure OpenAI tokens] ( /azure/ai-services/openai/overview#tokens ) and [ Azure OpenAI pricing] ( https://azure.microsoft.com/pricing/details/cognitive-services/openai-service/ ) .
170
195
0 commit comments