I recently came across with some very interesting feature in C# - Speech Synthesizer! Speech Synthesizer is Microsoft API which allows to build speech enabled applications. Just one row of code and your WPF application will spell any textual data!
All you need is just add a reference to System.Speech.Synthesis and a couple rows of code. I built a simple application just to show how to use Speech Synthesizer in WPF.
<TextBox Grid.Column="0" Grid.Row="0" HorizontalAlignment="Left" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Visible" FontSize="14" Height="100" Width="270" Name="TextBox_Read">Talk to me!</TextBox> <Button Grid.Column="1" Grid.Row="1" Name="Button_Say" Content="Say" Click="Button_Say_Click"></Button> <Button Grid.Column="1" Grid.Row="2" Name="Button_Who" Content="Who's talking?" Click="Button_Who_Click"></Button> <Slider Grid.Column="0" Grid.Row="1" Name="Slider_Volume" Value="50" Minimum="0" Maximum="100" TickFrequency="5" ValueChanged="VolumeChanged" ToolTip="Volume"/> <Slider Grid.Column="0" Grid.Row="2" Name="Slider_Rate" Value="0" Minimum="-5" Maximum="7" TickFrequency="1" ValueChanged="RateChanged" ToolTip="Speech Rate"/>
So, when user clicks on "Say" button, the Speech Synthesizer will spell what is currently written in the textbox. The upper slider is volume level and by the second slider we can change the speak rate. Let's see now the code behind:
public partial class MainWindow : Window { private SpeechSynthesizer _speechSynthesizer = new SpeechSynthesizer(); public MainWindow() { InitializeComponent(); } private void Button_Say_Click(object sender, RoutedEventArgs e) { _speechSynthesizer.SpeakAsync(TextBox_Read.Text); } private void VolumeChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { _speechSynthesizer.Volume = (int)((Slider)e.OriginalSource).Value; } private void RateChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { _speechSynthesizer.Rate = (int)((Slider)e.OriginalSource).Value; } private void Button_Who_Click(object sender, RoutedEventArgs e) { _speechSynthesizer.SpeakAsync("This is " + _speechSynthesizer.Voice.Name); } }
As you can see it is very easy to use speech synthesizer in WPF application. Just pass the text to SpeakAsync method and this is it!
Download the source code (Visual Studio 2010 project).
No comments:
Post a Comment