From ed92fd02279c2af5b43dc5ba4a70d1100bb4205b Mon Sep 17 00:00:00 2001 From: ste Date: Mon, 1 Jun 2020 17:06:50 +0100 Subject: [PATCH] Stopping speech if clicked while currently speaking --- .../ReadSelectedTextApp/MainWindow.xaml.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/ReadSelectedText/ReadSelectedTextApp/MainWindow.xaml.cs b/ReadSelectedText/ReadSelectedTextApp/MainWindow.xaml.cs index 9e90589..93ad829 100644 --- a/ReadSelectedText/ReadSelectedTextApp/MainWindow.xaml.cs +++ b/ReadSelectedText/ReadSelectedTextApp/MainWindow.xaml.cs @@ -4,6 +4,7 @@ using System.Windows; using System.Windows.Interop; using System.Speech.Synthesis; +using System.Threading; namespace ReadSelectedTextApp { @@ -14,7 +15,8 @@ public partial class MainWindow : Window { private WindowInteropHelper nativeWindow; private SelectionReader selectionReader; - private IntPtr environmentWindow; + private readonly IntPtr environmentWindow; + private readonly SpeechSynthesizer speech = new SpeechSynthesizer(); public MainWindow() { @@ -40,10 +42,16 @@ private async void Button_Click(object sender, RoutedEventArgs e) private async Task SaySelection(IntPtr? activeWindow = null) { - string text = await this.selectionReader.GetSelectedText(activeWindow); - SpeechSynthesizer speech = new SpeechSynthesizer(); - speech.SetOutputToDefaultAudioDevice(); - speech.SpeakAsync(text); + if (this.speech.State != SynthesizerState.Ready) + { + this.speech.SpeakAsyncCancelAll(); + } + else + { + string text = await this.selectionReader.GetSelectedText(activeWindow); + this.speech.SetOutputToDefaultAudioDevice(); + this.speech.SpeakAsync(text); + } } private async void Init(object sender, RoutedEventArgs e)