Want to add speech to any of your apps running in Windows? It’s pretty easy using the SpeechSynthesizer in the .NET Framework.
You can see this code in action in my Visual Studio backup or cleaner apps. I use text to speach to notifiy the user what the app is up to without having to watch the appliction. Makes it easier to know if there were any errors and when the app is finished.
In the Speak method below, just pass in the text you want the synthesizer to speak and this method will cancel anything currently being spoken and start speaking what ever you send in.
Imports System.Threading.Tasks Namespace Speech ''' <summary> ''' Synthesis helper methods. ''' summary> Public Module Synthesis ''' <summary> ''' _speech ''' summary> Private ReadOnly _speech As New System.Speech.Synthesis.SpeechSynthesizer() ''' <summary> ''' Speaks the specified text to speak. ''' summary> ''' <param name="textToSpeak">The text to speak.param> Public Sub Speak(ByVal textToSpeak As String) If _speech.GetInstalledVoices.Count > 0 Then _speech.SpeakAsyncCancelAll() _speech.Speak(textToSpeak) End If End Sub End Module
If you want speech to be async then you can use the SpeakAsync method below. This will speak any series of text sent into it, in order.
''' <summary> ''' Speaks the text asynchronously. ''' summary> ''' <param name="text">The text to speak.param> <Extension> Public Async Sub SpeakAsync(ByVal text As String) If String.IsNullOrWhiteSpace(text) Then Exit Sub End If Await Speech.SpeakAsync(text) End Sub
This code and more can be found in the dotNetTips.Utility open source project on GitHub.