Android TextToSpeech

时间:2011-12-10 13:37:55

标签: android

这是我的第一篇文章,希望你能帮助我:)。

我正在开发一个Android应用程序,但我无法理解为什么我的代码不起作用。 此应用程序识别语音执行某些命令。

public void OnButtonClick(View v)
{
    t.speak("Say the comand", TextToSpeech.QUEUE_FLUSH, null);
    startVoiceRecognitionActivity();//This is another function (Speech input)       
}

但我听不到TextToSpeech。

但如果我尝试这个代码就可以了:

public void OnButtonClick(View v)
{
    t.speak(x, TextToSpeech.QUEUE_FLUSH, null);
    while (t.isSpeaking()); //It wait the end of the speech
    startVoiceRecognitionActivity();//This is another function (Speech input)       
}

没关系,但是如果我在语音输入后尝试这段代码,它什么都不说:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
    {
        ArrayList<String> matches = data.getStringArrayListExtra(
                RecognizerIntent.EXTRA_RESULTS);
        b.setText(matches.get(0));
        Act(matches.get(0)); //Call the function to do a comand
    }
    super.onActivityResult(requestCode, resultCode, data);
}

public void Act(String cmd){
    if(cmd.equalsIgnoreCase("time") || cmd.equalsIgnoreCase("what time is it")){
        t.speak(x, TextToSpeech.QUEUE_FLUSH, null); //don't speach!
            while (t.isSpeaking());
    }   
}

我需要创建一个单独的线程,还是有更好的解决方案?

感谢所有人:)

P.S。对不起我的英文

2 个答案:

答案 0 :(得分:0)

尝试在Act(String cmd)方法中添加一个日志命令,以查看TTS识别的内容(可能是Android无法识别命令):

public void Act(String cmd){
    Log.d("MyTTSApp", cmd);
    if(cmd.equalsIgnoreCase("time") || cmd.equalsIgnoreCase("what time is it")){
        t.speak(x, TextToSpeech.QUEUE_FLUSH, null); //don't speach!
            while (t.isSpeaking());
    }   
}

答案 1 :(得分:0)

这与TextToSpeech在Android中的工作方式有关。

致电时

t.speak("Say the comand", TextToSpeech.QUEUE_FLUSH, null);

你说的是“现在开始说这个”。但是在下一行,你调用一个函数(我从名字中猜测)打开一个新的Activity,在它甚至有机会开始说话之前为你的第一个做背景。

有几种方法可以解决这个问题:你当前的修复并不是最糟糕的想法。或者,也许更整洁,而不是传递null作为最后一个要说的参数,传递一个实现onUtteranceCompletedListener的对象。当该对象的方法onUtteranceCompleted被调用时,然后调用startVoiceRecognitionActivity

相关问题