如何在MVVMCross插件中使用Android TextToSpeak?

如何在MVVMCross插件中使用Android TextToSpeak?,android,xamarin,mvvmcross,Android,Xamarin,Mvvmcross,我已经看到了很多关于如何在活动中使用Android TextToSpeak的例子,并且也成功地使其正常工作。我还设法在插件中使用绑定服务使其工作,但就我的目的而言,它似乎过于复杂了。这是我的语音服务课: public class VoiceService : IVoiceService, TextToSpeech.IOnInitListener { public event EventHandler FinishedSpeakingEventHandler; private T

我已经看到了很多关于如何在活动中使用Android TextToSpeak的例子,并且也成功地使其正常工作。我还设法在插件中使用绑定服务使其工作,但就我的目的而言,它似乎过于复杂了。这是我的语音服务课:

public class VoiceService : IVoiceService, TextToSpeech.IOnInitListener
{
    public event EventHandler FinishedSpeakingEventHandler;

    private TextToSpeech _tts;

    public void Init()
    {
        // Use a speech progress listener so we get notified when the service finishes speaking the prompt
        var progressListener = new SpeechProgressListener();
        progressListener.FinishedSpeakingEventHandler += OnUtteranceCompleted;

        //_tts = new TextToSpeech(Application.Context, this);
        _tts = new TextToSpeech(Mvx.Resolve<IMvxAndroidCurrentTopActivity>().Activity, this);
        _tts.SetOnUtteranceProgressListener(progressListener);
    }

    public void OnInit(OperationResult status)
    {

        // THIS EVENT NEVER FIRES!

        Console.WriteLine("VoiceService TextToSpeech Initialised. Status: " + status);
        if (status == OperationResult.Success)
        {

        }
    }

    public void Speak(string prompt)
    {

        if (!string.IsNullOrEmpty(prompt))
        {
            var map = new Dictionary<string, string> { { TextToSpeech.Engine.KeyParamUtteranceId, new Guid().ToString() } };
            _tts.Speak(prompt, QueueMode.Flush, map);

            Console.WriteLine("tts_Speak: " + prompt);
        }
        else
        {
            Console.WriteLine("tts_Speak: PROMPT IS NULL OR EMPTY!");
        }
    }

    /// <summary>
    /// When we finish speaking, call the event handler
    /// </summary>
    public void OnUtteranceCompleted(object sender, EventArgs e)
    {
        if (FinishedSpeakingEventHandler != null)
        {
            FinishedSpeakingEventHandler(this, new EventArgs());
        }
    }

    public void Dispose()
    {
        //throw new NotImplementedException();
    }

    public IntPtr Handle { get; private set; }
}
执行此操作时,我会在输出中获得以下消息:

10-13 08:13:59.734 I/TextToSpeech(2298):成功绑定到com.google.android.tts (在创建新的TTS对象时发生)

10-13 08:14:43.924 W/TextToSpeech(2298):讲话失败:未绑定到TTS引擎 (当我呼叫tts.Speak(提示)时)

如果我正在使用一个活动,我会创建一个让它工作的意图,但我不确定如何在插件中做到这一点

提前感谢,


David

不要自己实现
Handle
,而是从
Java.Lang.Object

public class VoiceService : Java.Lang.Object, IVoiceService, TextToSpeech.IOnInitListener
并删除您的
Dispose()
Handle
实现

更多信息请点击此处:

此外,我建议您在实现服务时采用异步方法,这将使从视图模型调用它类似于

await MvxResolve<ITextToSpeechService>().SpeakAsync(text);
wait MvxResolve().SpeakAsync(文本);

谢谢@Andrei,它源于Java.Lang.Object,解决了我的问题,我现在也重新考虑使用建议的异步方法,使代码更简单。很高兴听到这个消息!异步是伟大的
await MvxResolve<ITextToSpeechService>().SpeakAsync(text);