0

我一直在尝试将语音转文本添加到我的 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 但我无法返回结果。

4

1 回答 1

1

如果你得到了"Android.Content.ActivityNotFoundAcception".因为 xamarin Dependencyservice 只是有活动,而AndroidSpeech不是活动,你不要StartActivityForResult直接使用。解决方案是获取对当前活动的引用,为了做到这一点,我们将添加一个名为的 nugetPlugin.Current activity

您可以在我们的应用程序类中添加活动回调,所以我的应用程序类看起来像这样

  [Application]
public class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
    public MainApplication(IntPtr handle, JniHandleOwnership transer)
      : base(handle, transer)
    {
    }

    public override void OnCreate()
    {
        base.OnCreate();
        RegisterActivityLifecycleCallbacks(this);
        //A great place to initialize Xamarin.Insights and Dependency Services!
    }

    public override void OnTerminate()
    {
        base.OnTerminate();
        UnregisterActivityLifecycleCallbacks(this);
    }

    public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
    {
        CrossCurrentActivity.Current.Activity = activity;
    }

    public void OnActivityDestroyed(Activity activity)
    {
    }

    public void OnActivityPaused(Activity activity)
    {
    }

    public void OnActivityResumed(Activity activity)
    {
        CrossCurrentActivity.Current.Activity = activity;
    }

    public void OnActivitySaveInstanceState(Activity activity, Bundle outState)
    {
    }

    public void OnActivityStarted(Activity activity)
    {
        CrossCurrentActivity.Current.Activity = activity;
    }

    public void OnActivityStopped(Activity activity)
    {
    }
}

在 AndroidSpeech 类中,您可以像这样获得对当前活动的引用

_activity = CrossCurrentActivity.Current.Activity;

StartActivityForResult然后你可以打电话AndroidSpeech

有关于如何逐步实现语音转文本的博客,可以参考。 https://medium.com/@dev.aritradas/xamarin-forms-speech-recognition-c16f07cdf164

这是演示。 https://github.com/dev-aritra/XFSpeech

更新 这是正在运行的 GIF。

在此处输入图像描述

于 2019-03-29T08:49:14.617 回答