【发布时间】:2017-03-29 14:07:56
【问题描述】:
我现在真的卡住了,我对 Xamarin 很陌生。 我使用 Xamarin Forms 开发具有语音识别功能的应用程序。
我只创建了一个带有按钮和输入框的简单 UI。
工作:
- 按下按钮并显示带有语音识别的弹出窗口
- 将口语读入 var
不工作:
- 将数据传回 Xamarin Forms UI(条目)
StartPage.xaml.cs:
private void BtnRecord_OnClicked(object sender, EventArgs e)
{
WaitForSpeechToText();
}
private async void WaitForSpeechToText()
{
EntrySpeech.Text = await DependencyService.Get<Listener.ISpeechToText>().SpeechToTextAsync();
}
ISpeechToText.cs:
public interface ISpeechToText
{
Task<string> SpeechToTextAsync();
}
调用本机代码。
SpeechToText_Android.cs:
public class SpeechToText_Android : ISpeechToText
{
private const int VOICE = 10;
public SpeechToText_Android() { }
public Task<string> SpeechToTextAsync()
{
var tcs = new TaskCompletionSource<string>();
try
{
var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Sprechen Sie jetzt");
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);
try
{
((Activity)Forms.Context).StartActivityForResult(voiceIntent, VOICE);
}
catch (ActivityNotFoundException a)
{
tcs.SetResult("Device doesn't support speech to text");
}
}
catch (Exception ex)
{
tcs.SetException(ex);
}
return tcs.Task;
}
}
MainActivity.cs:
protected override void OnActivityResult(int requestCode, Result resultVal, Intent data)
{
if (requestCode == VOICE)
{
if (resultVal == Result.Ok)
{
var matches = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
if (matches.Count != 0)
{
string textInput = matches[0].ToString();
if (textInput.Length > 500)
textInput = textInput.Substring(0, 500);
}
// RETURN
}
}
base.OnActivityResult(requestCode, resultVal, data);
}
首先我认为我可以通过
return tcs.Task;
回到 ui,但后来我注意到这个返回发生在 语音识别的弹出窗口已完成渲染。这一刻,一句话也没说。
口语在 OnActivityResult 函数中的字符串“textInput”中, 但是我怎样才能将此字符串传递回 Xamarin.Forms UI?
谢谢大家!
【问题讨论】:
-
SpeechToTextAsync 需要用 async 关键字标记。
标签: c# android xamarin xamarin.android xamarin.forms