Skip to content

Text-to-Speech in C#

This page was automatically generated by AI; not yet reviewed for accuracy...

The content and code samples on this page were generated by using the ai CLI with customized prompts in this repository.

It's cool, but, it's experimental. 😁

Please review the content and code before using it in your application.

This sample demonstrates how to use the Azure Text-to-Speech API in a C# console application.

Program.cs

How to generate this sample
Command
ai dev new text-to-speech --csharp
Output
AI - Azure AI CLI, Version 1.0.0
Copyright (c) 2024 Microsoft Corporation. All Rights Reserved.

This PUBLIC PREVIEW version may change at any time.
See: https://aka.ms/azure-ai-cli-public-preview

Generating 'text-to-speech' in 'text-to-speech-cs' (2 files)...

TextToSpeech.csproj
Program.cs

Generating 'text-to-speech' in 'text-to-speech-cs' (2 files)... DONE!

Program.cs

STEP 1: Read the configuration settings from environment variables.

Program.cs
var speechKey = Environment.GetEnvironmentVariable("AZURE_AI_SPEECH_KEY") ?? "<insert your Speech Service API key here>";
var speechRegion = Environment.GetEnvironmentVariable("AZURE_AI_SPEECH_REGION") ?? "<insert your Speech Service region here>";
var voiceName = "en-US-AndrewNeural"; // You can list voice names with `ai speech synthesize --list-voices`

STEP 2: Create instances of a speech config and audio config, and set the voice name to use.

Program.cs
var config = SpeechConfig.FromSubscription(speechKey, speechRegion);
var audioConfig = AudioConfig.FromDefaultSpeakerOutput();
config.SpeechSynthesisVoiceName = voiceName;

STEP 3: Create the speech synthesizer from the above configuration information.

Program.cs
using (var synthesizer = new SpeechSynthesizer(config, audioConfig))

STEP 4: Get text from the user to synthesize.

Program.cs
Console.Write("Enter text: ");
var text = Console.ReadLine();

STEP 5: Start speech synthesis, and return after it has completed.

Program.cs
var result = await synthesizer.SpeakTextAsync(text);

STEP 6: Check the result.

Program.cs
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
    Console.WriteLine($"SYNTHESIZED: {result.AudioData.Length} byte(s)");
}
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?");
    }
}