2017-09-27 59 views
0

我在c#UWP中有这个简单代码,其中与Windows.Media.SpeechSynthesis类应用程序合成第一个字符串,我的问题是合成第二个之后,第一个合成完成。我知道这是可能通过使包括STR1 + STR2,但在运行此代码是更复杂的场景中唯一的字符串,这是不可能的。(对不起,我的英语水平较低)如何在异步函数结束时启动函数c#UWP

public MainPage() 
    { 
     this.InitializeComponent(); 
     string str1 = "weather data"; 
     talk(Textmeteo); 
     string str2 = "hello world"; 
     talk(str2); 
    } 

    public async void talk(string text) 
    { 
     // The media object for controlling and playing audio. 
     MediaElement mediaElement = new MediaElement(); 

     // The object for controlling the speech synthesis engine (voice). 
     SpeechSynthesizer synth = new SpeechSynthesizer(); 

     // Generate the audio stream from plain text. 


     SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text); 

     // Send the stream to the media object. 
     mediaElement.SetSource(stream, stream.ContentType); 
     mediaElement.Play(); 

    } 
+0

为什么'str1 + str2'不能在你的场景中使用? – AVK

+0

@AVK由于第一种情况下str1被合成,一个函数运行http请求来在线读取组成str2的数据。在第二种情况下,我需要一个指向第一个合成结束的数据,所以我开始语音识别。 –

回答

2

像往常一样,使用async方法返回void而不是TaskTask<T>是个好主意。
当您返回一个Task,你可以简单地添加的延续与ContinueWith

public MainPage() 
{ 
    this.InitializeComponent(); 
    string str1 = "weather data"; 
    Task talkingTask = talk(Textmeteo); 
    string str2 = "hello world"; 
    talkingTask = talkingTask.ContinueWith(completedTask => talk(str2)); 
} 

public async Task talk(string text) 
{ 
    // await... 
} 
+0

请问如何使用:talkingTask = talkingTask.ContinueWith(completedTask => talk(str2)); –

+0

@MilleHobby就是这样。你的'async talk'方法返回一个'Task'(这是由编译器完成的),并且'ContinueWith'告诉它在前一个完成时启动下一个'Action'(参数)。 –

+0

所以如果有10个字符串,'ContinueWith'应该重复10次? – AVK

2

使该方法talk返回Task而不是void

public MainPage() 
{ 
    this.InitializeComponent(); 
    MakeTalk(); 
} 

private async void MakeTalk() 
{ 
    // Surround by a try catch as we have async void. 
    string str1 = "weather data"; 
    await talk(Textmeteo); 
    string str2 = "hello world"; 
    await talk(str2); 
} 

public async Task talk(string text) 
{ 
    // [...] 
}