Last active
April 3, 2025 02:17
-
-
Save gostrafx/b6a73b4da6af4267c4e7a52671014dc0 to your computer and use it in GitHub Desktop.
C# Text to Speech Synthesis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Speech.Synthesis; | |
class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
// dotnet add package System.Speech | |
using (var speechSynthesizer = new SpeechSynthesizer()) | |
{ | |
// https://support.microsoft.com/windows/appendix-a-supported-languages-and-voices-4486e345-7730-53da-fcfe-55cc64300f01 | |
GetAllVoices(speechSynthesizer); | |
speechSynthesizer.SetOutputToDefaultAudioDevice(); | |
var color = new Prompt("What is your favorite color?"); | |
SetVoiceByLanguage("us-US", speechSynthesizer); | |
speechSynthesizer.Volume = 100; | |
speechSynthesizer.SpeakAsync(color); | |
Console.ReadKey(); | |
} | |
} | |
private static void SetVoiceByLanguage(string languageCode, SpeechSynthesizer synthesizer) | |
{ | |
foreach (var voice in synthesizer.GetInstalledVoices()) | |
{ | |
if (voice.VoiceInfo.Culture.Name != languageCode) continue; | |
synthesizer.SelectVoice(voice.VoiceInfo.Name); | |
Console.WriteLine("Selected Voice: " + voice.VoiceInfo.Name); | |
return; | |
} | |
Console.WriteLine("No voice found for language: " + languageCode); | |
} | |
private static void GetAllVoices(SpeechSynthesizer speechSynthesizer) | |
{ | |
foreach (var voice in speechSynthesizer.GetInstalledVoices()) | |
{ | |
var info = voice.VoiceInfo; | |
Console.WriteLine($"Name:{info.Name}"); | |
Console.WriteLine($"Culture: {info.Culture} {Environment.NewLine}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment