我正在使用 VS2019 开发一个 winforms 应用程序。当表单关闭时,我试图停止讲话。我有一个由以下代码显示的类:
public static class Voice
{
static SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
static Random rnd = new Random();
public static void Speak1()
{
speechSynthesizer.SpeakAsyncCancelAll();
speechSynthesizer.Volume = 100;
speechSynthesizer.Rate = -1;
speechSynthesizer.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
int choice = rnd.Next(1, 7);
switch (choice)
{
.....
}
}
public static void Speak2(bool tryAgain)
{
speechSynthesizer.SpeakAsyncCancelAll();
speechSynthesizer.Volume = 100;
speechSynthesizer.Rate = -1;
speechSynthesizer.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
int choice = rnd.Next(1, 3);
switch (choice)
{
//...
}
if (tryAgain)
{
speechSynthesizer.SpeakAsync("Try Again!");
}
}
public static void ReadAloud(string message)
{
speechSynthesizer.SpeakAsyncCancelAll();
speechSynthesizer.Volume = 100;
speechSynthesizer.Rate = -1;
speechSynthesizer.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);
speechSynthesizer.SpeakAsync(message);
}
public static void StopVoice()
{
speechSynthesizer.SpeakAsyncCancelAll();
}
}
我从解决方案中的多个位置调用方法。我的问题是,当我想通过在表单关闭时调用 StopVoice 方法来停止语音合成器时,我收到错误消息:
System.OperationCanceledException: '异步操作已取消。'
我该如何解决这个错误?