我一直在尝试将语音转文本添加到我的 android 应用程序中,但我不断收到“Android.Content.ActivityNotFoundAcception”。
我正在使用 android 5.0 (lollipop) 模拟器,因为我的电脑无法启动任何其他模拟器。
界面:
public interface ISpeech
{
Task<string> SpeechToTextAsync();
}
创建意图和启动活动:
// When i remove Java.Lang.Object it gives Java.Lang.NullPointer Exception
public class AndroidSpeech : Java.Lang.Object, ISpeech
{
public static AutoResetEvent autoEvent = new AutoResetEvent(false);
private Intent voiceIntent;
public static readonly int speech = 10; // requestCode
public static string speechResults;
public async Task<string> SpeechToTextAsync()
{
var context = Forms.Context;
var activity = (Activity)context;
voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak");
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);
autoEvent.Reset();
activity.StartActivityForResult(voiceIntent, speech);
await Task.Run(() => { autoEvent.WaitOne(new TimeSpan(0, 0, 3)); });
return speechResults;
}
}
在获得 OnActivityResult 之前它工作正常,这里它抛出异常
Main Activity:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (requestCode == AndroidSpeech.speech)
{
// resultCode returns Result.Canceled
if (resultCode == Result.Ok) // here it throws ActivityNotFoundException
{
var speech = data.GetStringArrayListExtra(RecognizerIntent.ExtraResults);
AndroidSpeech.speechResults = speech[0];
}
AndroidSpeech.autoEvent.Set();
}
base.OnActivityResult(requestCode, resultCode, data);
}
单击按钮时调用函数:
private async void OnStartBtnClick(object sender, EventArgs args)
{
string speechResults = await DependencyService.Get<ISpeech().SpeechToTextAsync();
Lbl.Text = speechResults;
}
我也试过:
[Activity]
public class AndroidSpeech : Activity, ISpeech
{
// this gives Java.Lang.NullPointer Exception
}
而且我还尝试创建自己的 RecognitionListener 但我无法返回结果。