SpeechSynthesizer class provides access to the functionality of an installed speech synthesis engine (voice).
Step 1: Open a blank app and add a Button and A TextBox either from the toolbox or by copying the following XAML code into your grid.
- <TextBlock Text="Speech Synthesis" FontSize="20" Margin="10,0,0,0"></TextBlock>
- <StackPanel Margin="10,40,0,0">
- <TextBlock Text="Type the text to speak" VerticalAlignment="Center" FontSize="20"></TextBlock>
- <TextBox Name="textToSpeak" TextWrapping="Wrap" Width="300" Height="50" Margin="0,15,0,0" HorizontalAlignment="Left"></TextBox>
- <Button Name="speak" Content="Speak" Margin="0,15,0,0" Width="100" Height="30" Click="speak_Click"></Button>
- <MediaElement Name="media" AutoPlay="False"></MediaElement>
- </StackPanel>
Step 2: Add the following namespaces to your project which is needed in further C# code.
- using Windows.Media.SpeechSynthesis;
Step 3: Copy and paste the following code to the cs page which will be called on button click and will speak the text in the TextBox.
- private async void speak_Click(object sender, RoutedEventArgs e)
- {
- SpeechSynthesizer synthesizer = new SpeechSynthesizer();
- SpeechSynthesisStream synthesisStream = await synthesizer.SynthesizeTextToStreamAsync(textToSpeak.Text);
- media.AutoPlay = true;
- media.SetSource(synthesisStream, synthesisStream.ContentType);
- media.Play();
- }
Step 4: Run your application and test yourself.