我正在运行一个正常工作的函数,但是我得到了正确的值,但是我在弄清楚如何从我的DI服务中获取值(即带有文本的字符串)回到我的共享代码时遇到了问题。当我在下面的函数中的日志中输入结果时,我得到正确的值:
RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) =>
{
thetextresult = result.BestTranscription.FormattedString;
System.Diagnostics.Debug.WriteLine(thetextresult); //I get the correct value
});
(如果我等待上面的代码可以解决我的问题吗?如果是这样,我怎样才能等待字符串的结果?)
我目前的问题是,在此代码之后,我再次使用日志来查看在此功能之后是否可以再次访问日志:
System.Diagnostics.Debug.WriteLine("Do I reach this?");
但我无法达到这一点,因此函数末尾的return thetextresult
未达到,这意味着我在共享代码中没有得到回报。
这是代码的外观:
我的iOS DependecyService中的功能:
var node = AudioEngine.InputNode;
var recordingFormat = node.GetBusOutputFormat(0);
node.InstallTapOnBus(0, 1024, recordingFormat, (AVAudioPcmBuffer buffer, AVAudioTime when) =>
{
LiveSpeechRequest.Append(buffer);
});
AudioEngine.Prepare();
NSError error;
AudioEngine.StartAndReturnError(out error);
RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) =>
{
thetextresult = result.BestTranscription.FormattedString;
System.Diagnostics.Debug.WriteLine(thetextresult); //value gets out correctly.
});
}
System.Diagnostics.Debug.WriteLine("Do I reach this?"); //this does not get reached when i do the function.
return thetextresult; //which means that this is not returning the value
}
接口:
public interface ISoundToSpeak
{
Task<string> SpeechToTextAsync();
}
我如何在我的内容页面上使用它,功能:
async Task <string>WaitForSpeech()
{
return await DependencyService.Get<ISoundToSpeak>().SpeechToTextAsync();
}
按钮:
async void speakClick(object s, EventArgs a)
{
var speechText = await WaitForSpeech();
System.Diagnostics.Debug.WriteLine(speechText); //so with this current code i do not get the text out in my shared code.
}
答案 0 :(得分:1)
你的函数StartRecord是异步的,但我没有看到它内部有任何等待。 SpeechRecognizer.GetRecognitionTask是一个带回调的任务。你应该能够达到&#34;我能达到这个目标吗?&#34;但是,由于你不等到GetRecognitionTask完成,因此结果不会存在。您应该以某种方式等待RecognitionTask或者不从函数返回textresult,而是从回调中调用您的共享代码。
最终有效的是为SpeechToTextAsync提供回调函数。