0%

20230202 測試 Microsoft.CognitiveServices.Speech 認知語音服務

測試 Microsoft.CognitiveServices.Speech 認知語音服務

建立測試專案

1
2
3
4
5
6
7
cd C:\hankchanggss_public

dotnet new console -f net6.0 -n MSText2SpeechDemo

cd ./MSText2SpeechDemo

dotnet add package Microsoft.CognitiveServices.Speech

new_proj

可執行的程式碼

  • 依照以下程式即可執要文字轉語音
  • 金鑰及設定依自己狀況替換

MSText2SpeechDemo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using Microsoft.CognitiveServices.Speech;

var contents = new string[]{
"文字測試段落一"
,"測試段落二"
,"三"
};

var path = "target/path";

foreach (var content in contents)
{
await SynthesisToSpeakerAsync("YourSubscriptionKey", "YourServiceRegion", "YourVoiceName", content, path);
}

//sample code from
//https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/how-to-speech-synthesis?tabs=browserjs%2Cterminal&pivots=programming-language-csharp

//所有語音清單在後下網址可找到,例如: zh-TW-HsiaoChenNeural
//https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/language-support?tabs=tts&WT.mc_id=DOP-MVP-37580#text-to-speech
static async Task SynthesisToSpeakerAsync(string subscriptionKey, string region, string speechSynthesisVoiceName, string text, string path)
{
var config = SpeechConfig.FromSubscription(subscriptionKey, region);
config.SpeechSynthesisVoiceName = speechSynthesisVoiceName;

// Creates a speech synthesizer using the default speaker as audio output.
using (var synthesizer = new SpeechSynthesizer(config))
{
// Receive a text from console input and synthesize it to speaker.
using (var result = await synthesizer.SpeakTextAsync(text))
{
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
//save wav here
//Console.WriteLine($"Speech synthesized to speaker for text [{text}]");
System.IO.File.WriteAllBytes(path, result.AudioData);
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");

if (cancellation.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails=[{cancellation.ErrorDetails}]");
Console.WriteLine($"CANCELED: Did you update the subscription info?");
}
}
}
}
}