单击按钮尝试在uwp中停止SpeechSynthesizer

时间:2017-01-21 12:50:14

标签: xaml uwp

我试图在单击按钮时停止在uwp中的SpeechSynthesizer,并尝试再次单击相同的图标启动SpeechSynthesizer。任何帮助将不胜感激解决此问题。 XAML

<Image x:Name="Sound" Source="ABCD/sound_active.png"
                   RelativePanel.AlignBottomWithPanel="True"
                       RelativePanel.RightOf="Pause" Tapped="SoundTap"
                       Margin="17,0,0,0"
                   Width="40" Height="40"/>

C#代码

private void SoundTap(object sender, TappedRoutedEventArgs e)
        {           
            if ((Sound.Source as BitmapImage).UriSource == new Uri("ms-appx:///ABCD/Sound_active.png", UriKind.Absolute))
            {
                Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));                
                textToSpeech.Stop();

            }
            else
            {
                Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
                textToSpeech.Play();
            }
        }

public async void Prevevent(object sender, TappedRoutedEventArgs e)
        {
            currentIndex--;
            if (currentIndex < 0)
            {
                currentIndex = 0;
                return;
            }
            Alph_cap.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Cap_" + currentIndex + ".png"));
            Alph_small.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Sml_" + currentIndex + ".png"));            
            CapAlphaName.Text = CapsAlpha[currentIndex];
            SmallAlphaName.Text = SmallAlpha[currentIndex];
            var speechText = this.CapAlphaName.Text;
            if (speechText != "")
            {
                var synth = new SpeechSynthesizer();

                var speechStream =await synth.SynthesizeTextToStreamAsync(speechText);

                this.textToSpeech.AutoPlay = true;
                this.textToSpeech.SetSource(speechStream, speechStream.ContentType);
                this.textToSpeech.Play();
            }

        }

1 个答案:

答案 0 :(得分:0)

理解问题:

基本上,您正在寻找一个切换开关,以更简单的方式打开和关闭语音合成tts(文本到语音)。

解决方案:

这不可能更简单,从不如此,这就是你的做法。

  1. 创建一个Bool属性,例如:private IsTTSEnabled = false我们将其用作标记。
  2. 在你的图像上点击或点击,检查IsTTSEnabled的当前值并翻转它(如果为真则为假,如果为假则为真),例如:IsTTSEnable = !IsTTSEnable;
  3. 如果打开TTS或关闭TTS,现在放置一个if循环进行处理。此外,由于TTS是使用媒体元素完成的,因此您无需重新初始化TTS,简单暂停和播放媒体元素,或根据需要启动和停止媒体元素。
  4. 所以你的c#代码变成了:

        private bool IsTTSEnabled = false;
        private void SoundTap(object sender, TappedRoutedEventArgs e)
        {
            IsTTSEnabled = !IsTTSEnabled;
            if(IsTTSEnabled)
            {
                Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
                textToSpeech.Stop();
            }
            else
            {
                Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
                textToSpeech.Play();
            }
        }
    

    注意:使用数据绑定可以轻松实现此功能,以提供可扩展性和易管理性,但更简单的方法就像我已经说明的那样