2013-03-28 49 views
4

我为我的应用程序添加语音合成。它的作品,但问题是我不能取消演讲...例如,当我导航到另一个页面时,演讲继续...因此,我调用CancelAll()方法取消当前的演讲,但发生异常我不知道为什么。你知道有什么问题吗?在Windows Phone 8中取消语音合成

例外

A first chance exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in mscorlib.ni.dll 
An exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary 
An exception of type 'System.Threading.Tasks.TaskCanceledException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary 
The program '[2576] TaskHost.exe' has exited with code -1 (0xffffffff). 

我的代码:既然你想取消就可以使用IAsyncActionSpeakTextAsync返回而不是使用await异步操作

private SpeechSynthesizer synth = new SpeechSynthesizer(); 

    protected override void OnBackKeyPress(CancelEventArgs e) 
    { 
     //I tried to cancel also here but it's the same exception... 
    } 

    //method called when I press a button Cancel 
    private void ButtonCancelSpeech(object sender, EventArgs eventArgs) 
    { 
     try 
     { 
      synth.CancelAll(); 
     } 
     catch (TaskCanceledException) 
     { 
      //I arrive in this exception 
     } 
    } 

    private async void BtnSpeech_Click(object sender, EventArgs e) 
    { 
     IEnumerable<VoiceInformation> voices = from voice in InstalledVoices.All 
                where voice.Language.Substring(0, 2).Equals(LanguageApp.GetLangage2Characters()) 
                select voice; 
     if (voices.ElementAt(0) != null) 
     { 
      // Set the voice as identified by the query. 
      synth.SetVoice(voices.ElementAt(0)); 

      await synth.SpeakTextAsync(_place.Description); 
     } 
    } 

谢谢

回答

11

private SpeechSynthesizer synth = new SpeechSynthesizer(); 
private IAsyncAction task; 

private void ButtonCancelSpeech(object sender, EventArgs eventArgs) 
{ 
    try 
    { 
     //cancel the async task itself 
     task.Cancel(); 
    } 
    catch (TaskCanceledException) 
    { 

    } 
    } 

private void BtnSpeech_Click(object sender, EventArgs e) 
{ 
    IEnumerable<VoiceInformation> voices = from voice in InstalledVoices.All 
                where voice.Language.Substring(0, 2).Equals(LanguageApp.GetLangage2Characters()) 
                select voice; 
    if (voices.ElementAt(0) != null) 
    { 
     // Set the voice as identified by the query. 
     synth.SetVoice(voices.ElementAt(0)); 

     task = synth.SpeakTextAsync(_place.Description); 
    } 
} 
+1

完美,它的工作原理!谢谢 – Volkan 2013-03-28 13:02:36

+1

不客气:) – keyboardP 2013-03-28 13:07:31

+1

感谢,伙计。 – 2013-12-14 14:35:06