Example #1
0
        public static async Task <bool> ReadAloud(FunctionArgs args)
        {
            string action = args["action"];

            switch (action)
            {
            case "pause":
                App.Current.Logger.LogError("ReadAloud: pause not supported");
                break;

            case "stop":
            case "play":
                Functions.speechPlayer?.Stop();
                Functions.speechPlayer?.Dispose();
                Functions.speechPlayer = null;

                if (action == "stop")
                {
                    break;
                }

                App.Current.Logger.LogDebug("ReadAloud: Storing clipboard");
                IDataObject?clipboardData = Clipboard.GetDataObject();
                Dictionary <string, object?>?dataStored = null;
                if (clipboardData != null)
                {
                    dataStored = clipboardData.GetFormats()
                                 .ToDictionary(format => format, format => (object?)clipboardData.GetData(format, false));
                }

                Clipboard.Clear();

                // Get the selection
                App.Current.Logger.LogDebug("ReadAloud: Getting selected text");
                await SelectionReader.Default.GetSelectedText(System.Windows.Forms.SendKeys.SendWait);

                string text = Clipboard.GetText();

                // Restore the clipboard
                App.Current.Logger.LogDebug("ReadAloud: Restoring clipboard");
                Clipboard.Clear();
                dataStored?.Where(kv => kv.Value != null).ToList()
                .ForEach(kv => Clipboard.SetData(kv.Key, kv.Value));

                // Talk the talk
                SpeechSynthesizer     synth  = new SpeechSynthesizer();
                SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);

                speechPlayer = new SoundPlayer(stream.AsStream());
                speechPlayer.LoadCompleted += (o, args) =>
                {
                    speechPlayer.Play();
                };

                speechPlayer.LoadAsync();

                break;
            }

            return(true);
        }