我正在运行一个正常工作的函数,并且我得到了正确的值,但我在弄清楚如何从我的 DI 服务返回到我的共享代码时遇到问题(这是一个带有文本的字符串)。当我在下面的函数的日志中输入结果时,我得到了正确的值:
RecognitionTask = SpeechRecognizer.GetRecognitionTask (LiveSpeechRequest, (SFSpeechRecognitionResult result, NSError err) =>
{
thetextresult = result.BestTranscription.FormattedString;
System.Diagnostics.Debug.WriteLine(thetextresult); //I get the correct value
});
(如果我 await 上面的这段代码是否可以解决我的问题?如果可以,我如何等待字符串的结果?)
我目前的问题是,在这段代码之后我再次使用日志来查看我是否可以在这个函数之后再次访问日志:
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
}
接口(interface):
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.
}
最佳答案
您的函数 StartRecord 是异步的,但我没有看到其中有任何等待。 SpeechRecognizer.GetRecognitionTask 是一个带有回调的任务。您应该能够达到“我能达到这个目标吗?”但 textresult 的结果不会出现,因为您没有等到 GetRecognitionTask 完成。您应该以某种方式在 RecognitionTask 上等待,或者不从函数返回 textresult,而是从回调中调用共享代码。
最后起作用的是为 SpeechToTextAsync 提供回调函数。
关于c# - 如何从我的 iOS 依赖项服务 [Xamarin.Forms.iOS] 中的 Task<string> 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832689/