如何以编程方式关闭“Android 语音转文本”对话框



我是安卓编程的新手。目前,我正在安卓中研究语音转文本。如果用户这样做,我想以编程方式关闭语音输入提示什么都不说。

我应该怎么做?

这是代码。

public void startSpeech(View view) {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
            "Speak something");
    try {
        startActivityForResult(intent, 84);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),
                "Speech is currently not supported",
                Toast.LENGTH_LONG).show();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 84: {
            if (resultCode == RESULT_OK && data != null) {
                ArrayList<String> result = data
                      .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                // The spoken words...
            }
            // if user did not speak anything, then close the dialog.
            // ???
            break;
        }
    }
}

只需使用

finishActivity(REQ_CODE_SPEECH_INPUT);

您可以通过几秒钟的延迟并调用 finishActivity(84)

关闭

您可以在startSpeech方法中添加以下行之一或两者:

intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS,10); 

intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS,10); 

这是两者之间的区别 常量是:

EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS :停止收听语音后认为输入完成所需的时间。

EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS:我们停止听到语音后考虑输入可能完成所需的时间。

注意:这里10指定,10毫秒,您可以根据自己的方便逐个值更改值。

我能够通过使用语音识别器类来摆脱这个问题。这是链接 https://developer.android.com/reference/android/speech/SpeechRecognizer

最新更新