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

时间:2014-10-13 07:16:26

标签: android xamarin mvvmcross

我已经看到很多关于如何在Activity中使用Android TextToSpeak的示例,并且还设法使其工作得很好。我还设法使用插件中的绑定服务来使其工作,但它似乎过于复杂以达到我的目的。这是我的VoiceService类:

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; }
}

请注意,永远不会调用OnInit方法。

在我的视图模型中,我想这样做:

            _voiceService.Init();
            _voiceService.FinishedSpeakingEventHandler += _voiceService_FinishedSpeakingEventHandler;

            ... and then later ...

            _voiceService.Speak(prompt);

当我这样做时,我在输出中得到这些消息:

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(提示))

如果我正在使用某个活动,我会创建一个让它工作的意图,但我不确定如何在插件中执行此操作。

提前致谢,

大卫

1 个答案:

答案 0 :(得分:2)

不要自己实施Handle,而应来自Java.Lang.Object

public class VoiceService : Java.Lang.Object, IVoiceService, TextToSpeech.IOnInitListener

并删除您的Dispose()Handle实施

此处有更多信息:http://developer.xamarin.com/guides/android/advanced_topics/java_integration_overview/android_callable_wrappers/

另外,我建议您在实现服务时采用异步方法,这样可以从视图模型中调用它,如

await MvxResolve<ITextToSpeechService>().SpeakAsync(text);