首页 > 解决方案 > 取消选择项目时如何停止语音 Windows.Media.SpeechSynthesis

问题描述

我目前正在尝试添加功能以允许在我的应用程序中使用屏幕阅读器,并且一直在使用 Windows.Media.SpeechSynthesis 和 .GotFocus 在屏幕阅读设备选择按钮和标签时​​读出它们。

My issue however is that the speech doesn't stop when another item is selected so I have everything being read at once.

我曾尝试使用 .LostFocus 和 .Stop() 方法来尝试解决此问题,但遗憾的是无济于事。

有没有人幸运地在应用程序和项目选择中实现 SpeechSynthesis?

标签: c#uwpaccessibility

解决方案


这是我在我的一个应用程序中使用的一些相关代码,

我使用单个实例MediaElement来阅读文本。

static MediaElement ttsMediaElement;

这是将文本转换为流并读取它的方法。在方法开始时,我停止了MediaElement.

public static async Task ConvertTextToSpeechAndPlay(string text)
{
    if (ttsMediaElement != null)
            ttsMediaElement.Stop(); //stop the reading that has not finished, if any

    var voice = ChooseVoice(text); //select the preferred voice chosen by the user
    if (voice != null)
    {
        using (var synth = new SpeechSynthesizer())
        {
            synth.Voice = voice;

            SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);

            ttsMediaElement = new MediaElement();

            ttsMediaElement.SetSource(stream, stream.ContentType);
            ttsMediaElement.Play();
        }
    }   
}

推荐阅读